您现在的位置是:首页 > 学无止境 > Python 网站首页学无止境
Python爬虫(二)—— 使用requests
- Python
- 2018年9月16日 21:06
- 1489已阅读
- 18
概况:requests是一个十分强大的爬虫工具库,通过它我们可以更加方便的实现urllib的操作,如cookies、登录验证、代理设置。
一、安装requests
在ubuntu安装requests十分简便,只需要使用pip安装即可,在命令行输入
summer@hp:~ $ pip install requests
安装完成后验证是否安装成功只要在终端进入python环境,输入
summer@hp:~ $ python
Python 3.6.5 (default, Apr 1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>>
出现上述情况则说明安装成功。
二、基本用法
requests有很多方法来完成对应的请求,如get(),post(),put(),delete()等方法分别实现了GET、POST、PUT、DELETE等请求。
1.GET请求
- 构造一个最简单的get请求
import requests response = requests.get("http://httpbin.org/get") print(response.text)
{ "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "origin": "218.197.153.172", "url": "http://httpbin.org/get" }
- 构造一个带参数的GET请求:利用requests的params参数
import requests params = { 'addr': 'Wuhan', 'phone': '123456', } response = requests.get('http://httpbin.org/get/', params=params) print(response.text)
{ "args": { "addr": "Wuhan", "phone": "123456" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "origin": "218.197.153.172", "url": "http://httpbin.org/get?addr=Wuhan&phone=123456" }
- 带上请求头伪装浏览器获取网页:requests.get()拥有headers参数,可以让我们自行设置headers信息。通过设置headers信息我们可以将爬虫伪装成浏览器来骗过一些有反爬虫策略的网站。借用书中的例子
import requests import re headers = { 'User-Agent': 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36', } response = requests.get("https://www.zhihu.com/explore", headers=headers) pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S) titles = re.findall(pattern, response.text) print(titles)
['\n如何看待拼多多热卖的纸尿裤来自黑工厂?\n', '\n杨超越的颜值是否过誉了?\n', '\n在一个有爱的家庭里成长对一个人影响有多大?\n', '\n有哪些食物为了健康你一定不吃?\n', '\n有什么是你去了北京才知道的事情?\n', '\n西班牙在殖民开拓时期,加泰罗尼亚人,加西利亚人,巴斯克人扮演角色如何?\n', '\n如果换成卢姥爷和寒夜护撕会怎样?\n', '\n人生应该活成什么样子,该以什么样的方式活着?\n', '\n哪个瞬间让你觉得中国动画产业真的完了?\n', '\n怎么看待现在全网的踩 aj 接吻以及相关回答?\n']
- 抓取二进制数剧。如果我们想要的数据不是html页面,而是一些图片,视频,音频的文件,那么我们怎么获取呢?在requests中,获取二进制数据我们只需要使用 .content 而不是 .text 。就能获取到bytes类型的数据,然后将其写入对应扩展名相同的文件就OK了。
2.POST请求
- 对于另一种常见的post请求,我们可以使用requests的post()方法,利用data参数来传输我们需要传输的数据。示例如下
import requests data = {'name': 'Lily', 'age': '18'} response = requests.post("http://httpbin.org/post", data=data) print(response.text)
{ "args": {}, "data": "", "files": {}, "form": { "age": "18", "name": "Lily" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "16", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "json": null, "origin": "218.197.153.172", "url": "http://httpbin.org/post" }
3.响应
通过requests方法,我们也可以获取到其他信息,如状态码、响应头、cookies等
import requests
r= requests.get("http://www.jianshu.com")
print(type(t.status_code), r.status_code) # 获取状态码
print(type(t.headers), r.headers) # 获取响应头
print(type(t.cookies), r.cookies) # 获取cookies
print(type(t.url), r.url) # 获取URL
print(type(t.history), r.history) # 获取请求历史
三、高级用法
在上面我们了解到了requests的一些基本用法,下面我们再来了解一下requests的一些高级的用法,例如文件上传、cookies设置、代理设置等。
1.文件上传
requests不仅可以模拟提交一些数据,也可以用它来实现上传文件的功能,而且十分的简便,例子如下:
import requests
file = {
'file' : open('image.jpg', 'rb')
}
response = requests.post("http://httpbin.org/post", files=file)
print(response.text)
我们用一张同目录下名为image.jpg的图片来测试,得到返回结果为:
{
"args": {},
"data": "",
"files": {
"file": "data:application/octet-stream;base64,/9j/4AAQSkZJR......"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "77600",
"Content-Type": "multipart/form-data; boundary=4d831e06e7c746aa82e7f7aaa4e29db9",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.172",
"url": "http://httpbin.org/post"
}
说明上传文件会有一个单独的files字段来标识
2.Cookies
首先看一下如何使用requests来获取cookies
import requests
response = requests.get("https://www.baidu.com")
print(response.cookies)
for k, v in response.cookies.items():
print(k + "=" + v)
结果如下:
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315
再来看一下如何使用cookies
① 直接将headers中的cookies 复制下来,然后将其设置到headers中,再去访问需要cookies访问的页面,就可以发现成功访问。如(下面例子中的cookies为测试cookies,无法使用)
import requests
headers = {
'cookies': 'pgv_pvi=2059012096; RK=BnIwHBcgQY; ptcz=e3835918b49f375434396aeef5f4d2ddf33bd2c7a1a82200f8150ddd406f069d; pgv_pvid=2366030028; tvfe_boss_uuid=42509b0db872824a; ts_uid=4923877945; tvfe_search_uid=aa07b4cc-d0cc-4456-8ef7-9b24af9c9eca; login_remember=qq; mobileUV=1_164b307a5b2_16422; ptui_loginuin=541603466; pt2gguin=o0541603466; o_cookie=541603466; ts_refer=www.baidu.com/s; uid=547585727; pgv_info=ssid=s3626400576; ptag=|videolist:click; pgv_si=s2010543104; ptisp=edu; uin=o0541603466; skey=@LX3KYT8gr; luin=o0541603466; lskey=000100009306d0ab7076dc5bc6426e7d7661b594cadae620d7e10f25edc9e5afefe78e290b3b6f892cff70f0; main_login=qq; vuserid=329304021; vusession=5f57640295c48b567230210d8ae2; encuin=9ee36b6f5dfe1af2a0b6c87bb849e22c|541603466; lw_nick=%20STudy|541603466|//thirdqq.qlogo.cn/g?b=sdk&k=UJia60KBIkJmLOEcsibj4rVQ&s=40&t=1528370775|1; qv_als=1Xz9DO4KixZja0UdA11537172207nkzTTQ==; ad_play_index=38; ts_last=v.qq.com/x/webtips',
'Host': 'www.zhihu.com',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'
}
r= requests.get('https://www.zhihu.com', headers=headers)
print(r.text)
3.会话维持
在requests中,如果直接用get()和post()等方法进行打开页面,就相当于用两个浏览器打开了不同的页面,这样就相当于是两个会话了。我们也就不能在post()登录之后在get()需要登录了才能获取到的页面。解决这个问题的方法就是维持一个会话,即只打开一个浏览器,但是用不同的标签页来打开不同的页面,在requests中我们有一个新的利器——Session对象
import requests
requests.get("http://httpbin.org/cookies/set/number/123456")
q = requests.get('http://httpbin.org/cookies')
print(q.text)
# 利用Session对象
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456')
r = s.get('http://httpbin.org/cookies')
print(r.text)
结果
{
'cookies': {}
}
{
'cookies': {
'number': '123456',
}
}
因此Session通常用于模拟登录成功后在进行下一步操作
4.代理设置
对于一些网站在测试的时候可以获取到内容,但是一旦开始大规模的请求的话,网站可能就会弹出验证码或者是直接封掉客户端的IP,导致一段时间内无法访问。为了防止这种情况的发生,我们就需要设置代理来解决这个问题,此时就要用到proxies参数。设置方式如下
import requests
proxies = {
'http': 'http://10.10.10.10:3125', # 测试IP,无效,需换成有效ip
'https': 'https://10.10.10.10:5774',
}
requests.get("https://www.taobao.com", proxies=proxies)
如果代理需要使用HTTP Basic Auth,代理也可以用类似http://user:passaoed@host:port的语法来设置代理。
同时除了基本的HTTP代理之外,requests还支持SOCKS协议代理,但是首先要安装socks的库,可使用pip install 'requests[socks]',
然后再用类似socks5://user:passaoed@host:port的语法来设置
版权声明:本文为博主原创文章,转载时请注明来源。https://blog.thinker.ink/passage/8/
上一篇:Python爬虫(一)