requests
模块简介
原文:https://www.studytonight.com/python/web-scraping/introduction-to-requests-module
requests
模块用于向任意服务器发送 HTTP 请求并接收回 HTTP 响应。因此我们将使用requests
模块使用网站的网址发送 HTTP 请求并返回响应,为此我们将使用美汤模块从响应中取出网站的有用数据/信息/内容。
那么我们来学习一下如何使用requests
模块发送 HTTP 请求和接收服务器的响应。
一些有用的request
模块方法
以下是requests
模块中用于发出 HTTP 请求的一些常用方法。
- requests.get()
- requests.post()
- requests.put()
- requests.delete()
- requests.head()
- requests.options()
在本教程中,我们将使用requests.get()
和requests.post()
方法对网页抓取进行 HTTP 请求。
如果你是 HTTP 请求新手,想知道 GET 和 POST 请求是什么,这里有一个简单的解释:
- GET :用于使用 URL 检索信息(网页)。
- POST :用于向某个 URL 发送信息。
使用requests.get
提出请求
requests.get(URL)
方法用于发送 HTTP 请求并接收数据作为响应。它需要一个网址或任何 API。
response.content
是存储响应内容的变量,是get()
方法的响应。
让我们举个例子,
## import requests module
import requests
## send a request and receive the information from https://www.google.com
response = requests.get("https://www.google.com")
## printing the response
print(response.content)
上述脚本的输出将是指定网址的整个页面源(或源代码),我们已经将其存储在下面的 文件 中(因为太长)。
你一定想知道我们怎么能从这里读到任何东西,因为它太复杂了。为了使响应内容可读,我们使用了BeautifulSoap模块,这将在接下来的教程中介绍。
我们可以使用response.headers
方法打印网站在回复中发送的标题信息。
对于新手来说,头信息包含关于 HTTP 连接的一般元信息以及一些连接属性。
让我们为上面的 get 请求打印标题:
## import requests module
import requests
## send a request and receive the information from https://www.google.com
response = requests.get("https://www.google.com")
## headers of the website
print(response.headers)
{ ' Date ':' 2018 年 11 月 07 日星期三 08:56:29 GMT ',' Expires ':-1 ',' Cache-Control': 'private,max-age=0 ',' Content-Type ':' text/html;charset=ISO-8859-1 ',' P3P': 'CP= '这不是 P3P 的政策!更多信息请见 g.co/p3phelp。”、“内容编码”:“gzip”、“服务器”:“gws”、“X-XSS-保护”:“1;mode=block ',' X-Frame-Options': 'SAMEORIGIN ',' Set-Cookie ':' 1P JAR = 2018-11-07-08;到期=Fri,07-12-2018 08:56:29 格林尼治时间;路径=/;domain=.google.com,NID = 144 = cpba w4 rax5 tzbz3 wtdnn 54 qgut 198 ovtvdywyx0ifipo-MLX qcq 8 djzxqnko 7 wqrd4d kognxshyh 9 tfmmzktoz0 oonbu-9nlw 50 ocpogmxvt 9 snrzgxpujgmv 0 d5a 7 urfesv 0 blihlp 24 upnwhoqjmo 5 sbznndc 0 dvd3d vr5s;到期时间= 2019 年 05 月 09 日星期四格林尼治时间 08:56:29;路径=/;domain = .google.comHttpOnly ',' Alt-Svc ':' quic = ":443 ";ma = 2592000v="44,43,39,35 " ','传输编码':'分块' }
为了以更易读的格式打印值,我们可以使用方法response.headers.items()
分别访问每个值,并使用 for
循环打印每个值。
## import requests module
import requests
## send a request and receive the information from https://www.google.com
response = requests.get("https://www.google.com")
## headers of the website
for key, value in response.headers.items():
print(key, '\t\t', value)
日期:2018 年 11 月 7 日星期三格林尼治时间 08:56:29 到期-1 缓存-控制私有,最大年龄=0 内容类型文本/html;charset=ISO-8859-1 P3P CP= "这不是 P3P 的政策!更多信息请见 g.co/p3phelp。”内容编码 gzip 服务器 GWS X-XSS-保护 1;模式=块 X-帧-选项 same origin Set-Cookie 1P JAR = 2018-11-07-08;到期=Fri,07-12-2018 08:56:29 格林尼治时间;路径=/;domain=.google.com,NID = 144 = cpba w4 rax5 tzbz3 wtdnn 54 qgut 198 ovtvdywyx0ifipo-MLX qcq 8 djzxqnko 7 wqrd4d kognxshyh 9 tfmmzktoz0 oonbu-9nlw 50 ocpogmxvt 9 snrzgxpujgmv 0 d5a 7 urfesv 0 blihlp 24 upnwhoqjmo 5 sbznndc 0 dvd3d vr5s;到期时间= 2019 年 05 月 09 日星期四格林尼治时间 08:56:29;路径=/;domain = .google.comHttpOnly Alt-Svc quic = ":443 ";ma = 2592000v =“44,43,39,35”传输编码分块
请求的状态
当我们使用requests.get()
方法发出 GET 请求时,请求可能会失败,被重定向到其他网址,可能会在客户端或服务器端失败,也可能会成功完成。
要了解请求的状态,我们可以查看收到的响应的状态代码。
这可以使用response.status_code
值来完成。很简单,
## import requests module
import requests
## send a request and receive the information from https://www.google.com
response = requests.get("https://www.google.com")
## status of request
print(response.status_code)
Two hundred
以下是您可能在响应中获得的不同状态值:
| 状态代码 | 描述 | | 1XX | 报告的 | | 2XX | 成功 | | 3XX | 重寄 | | 4XX | 客户端错误 | | 5XX | 服务器错误 |
例如: 200 状态码为成功。鉴于, 201 状态代码用于已创建(当我们发送创建某个资源的请求时)等。
就像 GET 请求一样,我们可以使用requests.post(URL)
方法发出 POST 请求,处理响应也是一样的。
对于网页抓取,我们将主要使用 GET 请求。
设置用户代理
当我们试图使用程序访问网站时,出于安全原因,一些网站不允许这样做,因为这使得网站容易受到通过程序生成的不必要请求的影响,在极端情况下,这些程序甚至会通过发送大量请求来加重网站服务器的负担。
为了克服这一点,我们将使用伪造用户代理模块,该模块用于伪造对服务器的请求,就好像它是由用户而不是程序发起的一样。
要安装模块 fake_useragent ,运行以下命令:
pip install fake_useragent
一旦安装完成,我们就可以用它来生成一个虚假的用户请求,如下所示:
## import UserAgent from the fake_useragent module
from fake_useragent import UserAgent
## create an instance of the 'UserAgent' class
obj = UserAgent()
## create a dictionary with key 'user-agent' and value 'obj.chrome'
header = {'user-agent': obj.chrome}
## send request by passing 'header' to the 'headers' parameter in 'get' method
r = requests.get('https://google.com', headers=header)
print(r.content)
这个请求的输出将是网页https://google.com的源代码,就好像它是由用户使用 Chrome 浏览器打开的一样。
所以现在我们知道如何使用requests
模块向任何网址发送一个 HTTP 请求并接收响应。在下一个教程中,我们将学习如何使用BeautifulSoap模块从 HTTP 响应中获取真正有用的内容。