python的requests库

requests是在爬虫中常用到的一个库,它可以帮助我们很好的去请求我们想要爬取的网站,并返回网站的内容。

0x01:请求

get请求、post请求这两个是最常用的请求方式,此外还有类似delete、head、options。

请求的参数

params/data:这个两个是传入请求时传给服务器的参数,params用于get中,data用于post中

headers:传入请求头

proxies:传入代理

timeout:超时设置

代码演示:

 1 import requests
 2 
 3 url = 'http://www.tianya.cn/'
 4 params = {'username': 'zhangan', 'password': 123456}
 5 header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0' }
 6 proxies = {
 7   "http": "http://10.10.1.10:3128",
 8   "https": "http://10.10.1.10:1080",
 9 }
10 
11 # html = requests.get(url=url, params=params, headers=header, proxies=proxies, timeout=1)
12 html = requests.get(url=url, params=params, headers=header)
13 print(html.url)
14 print(html.request.headers)

输出如下:
http://www.tianya.cn/?username=zhangan&password=123456
{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

第七行输出请求的url,可以看到,在get请求时params传入的参数被直接放在了后面,另外,我们在请求时利用headers参数设置了一个请求头,这样伪装成了浏览器,而不是我们使用的python requests。第八行,输出请求的请求头

如果需要设置代理和超时时间,像11行那样传入proxies和timeout参数就行了,由于这里的代理时无效的,所以没有运行,这又一个免费获取代理的网站,大家需要的话可以去这上面找:https://www.xicidaili.com/

0x02:获取

除了能够获取到url和请求头之外,还能获取到更多的内容。

获取网页源码:.text / .content 前者是以文本的方式获取,后者是以二进制的方式获取到。

获取状态码:.status_code

获取响应头:.headers

获取cookies:.cookies

稍微改一下上面的代码:

url = 'http://www.tianya.cn/'
params = {'username': 'zhangan', 'password': 123456}
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0' }
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}

# html = requests.get(url=url, params=params, headers=header, proxies=proxies, timeout=1)
html = requests.get(url=url, params=params, headers=header)
print(html.status_code)  # 获取状态码
print(html.headers)         # 获取响应头
print(html.cookies)         # 获取到cookies

输出结果如下:
200
{'Server': 'nginx', 'Date': 'Wed, 24 Jul 2019 10:57:06 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'Vary': 'Accept-Encoding', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': 'Thu, 01 Nov 2012 10:00:00 GMT', 'ETag': 'W/"6de10a5VRB4"', 'Last-Modified': 'Fri, 19 Jul 2019 09:40:47 GMT', 'Content-Encoding': 'gzip'}
<RequestsCookieJar[]>

依次输出了返回的状态码/服务器的响应头/cookies。

除此此外,requests还可保持会话维持,身份认证,SSL证书验证等。静谧大佬的爬虫文章写的很棒,大家可以参考下:https://cuiqingcai.com/5523.html

猜你喜欢

转载自www.cnblogs.com/liangxiyang/p/11066393.html
今日推荐