一 介绍
Python上有一个非常著名的HTTP库——requests,相信大家都听说过,用过的人都说非常爽!现在requests库的作者又发布了一个新库,叫做requests-html,看名字也能猜出来,这是一个解析HTML的库,具备requests的功能以外,还新增了一些更加强大的功能,用起来比requests更爽!接下来我们来介绍一下它吧。
# 官网解释 ''' This library intends to make parsing HTML (e.g. scraping the web) as simple and intuitive as possible. If you’re interested in financially supporting Kenneth Reitz open source, consider visiting this link. Your support helps tremendously with sustainability of motivation, as Open Source is no longer part of my day job. When using this library you automatically get: - Full JavaScript support! - CSS Selectors (a.k.a jQuery-style, thanks to PyQuery). - XPath Selectors, for the faint at heart. - Mocked user-agent (like a real web browser). - Automatic following of redirects. - Connection–pooling and cookie persistence. - The Requests experience you know and love, with magical parsing abilities. - Async Support '''
官网告诉我们,它比原来的requests模块更加强大,并且为我们提供了一些新的功能!
- 支持JavaScript
- 支持CSS选择器(又名jQuery风格, 感谢PyQuery)
- 支持Xpath选择器
- 可自定义模拟User-Agent(模拟得更像真正的web浏览器)
- 自动追踪重定向
- 连接池与cookie持久化
- 支持异步请求
二 安装
安装requests-html非常简单,一行命令即可做到。需要注意一点就是,requests-html只支持Python 3.6或以上的版本,所以使用老版本的Python的同学需要更新一下Python版本了。
# pip3 install requests-html
三 如何使用requests-html?
在我们学爬虫程序的时候用得最多的请求库就是requests与urllib,但问题是这些包只给我们提供了如何去目标站点发送请求,然后获取响应数据,接着再利用bs4或xpath解析库才能提取我们需要的数据。
import requests from bs4 import BeautifulSoup url = 'http://www.zuihaodaxue.cn/' HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36' } response = requests.get(url, headers=HEADERS) response.encoding = 'gbk' # print(response.status_code) # print(response.text) soup = BeautifulSoup(response.text, 'lxml') # 获取最新的五则新闻 post_rankings = soup.find_all(name='article', attrs={"class": "post_ranking"}) # 循环打印新闻简介内容 for post_ranking in post_rankings: new = post_ranking.find(name='div', attrs={"class": 'post_summary'}) print(new.text)
而在requests-html里面只需要一步就可以完成而且可以直接进行js渲染!requests的作者Kenneth Reitz 开发的requests-html 爬虫包 是基于现有的框架 PyQuery、Requests、lxml、beautifulsoup4等库进行了二次封装,作者将Requests的简单,便捷,强大又做了一次升级。
1、基本使用
from requests_html import HTMLSession # 获取请求对象 session = HTMLSession() # 往新浪新闻主页发送get请求 sina = session.get('https://news.sina.com.cn/') # print(sina.status_code) sina.encoding = 'utf-8' # 获取响应文本信息,与requests无区别 # print(sina.text)
2、获取链接(links与abolute_links)
links返回的结果 absolute_links返回的结果
from requests_html import HTMLSession # 获取请求对象 session = HTMLSession() # 往京东主页发送get请求 jd = session.get('https://jd.com/') # 得到京东主页所有的链接,返回的是一个set集合 print(jd.html.links) print('*' * 1000) # 若获取的链接中有相对路径,我们还可以通过absolute_links获取所有绝对链接 print(jd.html.absolute_links)
3、CSS选择器与XPATH
request-html支持CSS选择器和XPATH两种语法来选取HTML元素。首先先来看看CSS选择器语法,它需要使用HTML的 find 函数来查找元素。
''' CSS选择器 and XPATH 1.通过css选择器选取一个Element对象 2.获取一个Element对象内的文本内容 3.获取一个Element对象的所有attributes 4.渲染出一个Element对象的HTML内容 5.获取Element对象内的特定子Element对象,返回列表 6.在获取的页面中通过search查找文本 7.支持XPath 8.获取到只包含某些文本的Element对象 '''
from requests_html import HTMLSession session = HTMLSession() url = "https://www.qiushibaike.com/text/" # 获取响应数据对象 obj = session.get(url) # 1.通过css选择器选取一个Element对象 # 获取id为content-left的div标签,并且返回一个对象 content = obj.html.find('div#content-left', first=True) # 2.获取一个Element对象内的文本内容 # 获取content内所有文本 print(content.text) # 3.获取一个Element对象的所有attributes # 获取content内所有属性 print(content.attrs) # 4.渲染出一个Element对象的完整的HTML内容 html = content.html print(html) # 5.获取Element对象内的指定的所有子Element对象,返回列表 a_s = content.find('a') print(a_s) print(len(a_s)) # 79 # 循环所有的a标签 for a in a_s: # 获取a标签内所有属性的href属性 并拼接 href = a.attrs['href'] if href.startswith('/'): url = 'https://www.qiushibaike.com' + href print(url) # 6.在获取的页面中通过search查找文本 # {}大括号相当于正则的从头到后开始匹配,获取当中想要获取的数据 text = obj.html.search('把{}夹')[0] # 获取从 "把" 到 "夹" 字的所有内容 text = obj.html.search('把糗事{}夹')[0] # 获取从把子到夹字的所有内容 print(text) print('*' * 1000) # 7.支持XPath a_s = obj.html.xpath('//a') # 获取html内所有的a标签 for a in a_s: href = a.attrs['href'] # 若是//开头的url都扔掉 if href.startswith('//'): continue # 若是/开头的都是相对路径 elif href.startswith('/'): print('https://www.qiushibaike.com' + href) # 8.获取到只包含某些文本的Element对象(containing) # 获取所有文本内容为幽默笑话大全_爆笑笑话_笑破你的肚子的搞笑段子 - 糗事百科 title标签 # 注意: 文本内有空格也必须把空格带上 title = obj.html.find('title', containing='幽默笑话大全_爆笑笑话_笑破你的肚子的搞笑段子 - 糗事百科') print(title)