python requests下载网页_python爬虫 requests-html的使用

一 介绍

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的简单,便捷,强大又做了一次升级。

requests-html和其他解析HTML库最大的不同点在于HTML解析库一般都是专用的,所以我们需要用另一个HTTP库先把网页下载下来,然后传给那些HTML解析库。而requests-html自带了这个功能,所以在爬取网页等方面非常方便。

1、基本使用

from requests_html import HTMLSession

# 获取请求对象

session = HTMLSession()

# 往新浪新闻主页发送get请求

sina =

你可能感兴趣的:(python,requests下载网页)