常见Python爬虫工具总结

常见Python爬虫工具总结

前言

以前写爬虫都是用requests包,虽然很好用,不过还是要封装一些header啊什么的,也没有用过无头浏览器,今天偶然接触了一下。

原因是在处理一个错误的时候,用到了几个以前没有用过的工具;这几个工具也挺常见的,在这里一起总结一下。包括以下几个:

  • selenium
  • requests-html

selenium

简介

selenium是一个网页自动化测试的工具,既然是网页测试的,那么肯定支持各种浏览器了,常见的Firefox/Chrome/Safari都支持;当然,也需要你下载对应浏览器的驱动了。下面简单说一下他的使用方式。

安装
  • 使用pip install selenium安装selenium
  • 安装对应浏览器驱动,chrome的可以去这里下载
  • 把驱动copy到/usr/local/bin下(非必须,不拷贝的话在使用的时候需要制定驱动的路径)
简单使用
from selenium import webdriver

driver = webdriver.chrome.webdriver.WebDriver()
driver.get("https://www.lagou.com/jobs/3490584.html")

# 获取源码
a = driver.page_source.encode('utf-8')

# 查找资源/tag
driver.find_element_by_xpath(u"//img[@alt='强化学习 (Reinforcement Learning)']").click()
driver.find_element_by_link_text("About").click()

# 截图
driver.get_screenshot_as_file("./img/sreenshot1.png")

requests-html

简介

是不是看见requests很熟悉,没错,这个就是会拍照又会写代码的requests的作者写的又一个库;

这个库代码并不是很多,都是基于其他库封装的,lxml/requests啊这些;使用也很简单,遵循了他的宗旨:for humans

安装
pip install requests-html
使用
from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://python.org/')

# 获取页面上的链接
r.html.links
r.html.absolute_links

# 用css选择器选择一个元素
about = r.html.find('#about', first=True)
print(about.text)

# xpath
r.html.xpath('a')

参考

原文地址:https://www.cnblogs.com/wswang/p/9405915.html