2.爬虫之第三方库requests

requests库

虽然Python的标准库中urllib模块已经包含了我们平常使用的大多数网络请求的功能,但是它的API使用起来让人感觉不太友好,而requests库宣传是‘http for human’,所以使用更加简洁方便。对于设计简单的爬虫,强烈建议使用requests
利用pip可以非常方便的安装:

pip install requests

中文文档:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

1.简单使用

import requests

resp = requests.get('http://www.baidu.com')
print(resp.text)

2.添加headers和查询参数:

如果想添加headers,可以传入headers参数来增加请求头中的headers信息。如果要将参数放在url中传递,可以利用params参数。示例代码如下:

import requests

kw = {'word':'中国'}
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36'}

# params接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com",params=kw,headers=headers)

# 查询响应内容,resposne.text返回的是Unicode格式数据
print(response.text)

# 查询响应内容,resposne.content返回的是字节流数据
print(response.content)

# 查看完整的url
print(response.url)

# 查看响应头部字符编码
print(response.encoding)

# 查看响应码
print(response.status_code)

response.textresponse.content的区别

  1. response.content:这个是直接从互联网上面抓取的数据。没有经过任何的解码。所以是一个bytes类型。其实在硬盘上和在网络上传输的字符串都是bytes类型
  2. response.text:这个是str数据类型,是requests库将response.content进行编码的字符串。解码需要指定一个编码方式,requests会根据自己的猜测来判断编码的方式。所以有时候可能会猜测错误,就会导致解码产生乱码。这时候就应该使用response.content.decode('utf-8')进行手动解码。

发送post请求

1.最基本的post请求可以使用post方法

response = requests.post('http://www.baidu.com',data=data)

2.传入data数据
这时候就不要使用urlencode进行编码了,直接传入一个字典进去就可以了。比如请求拉钩网的数据(拉钩网上的职位信息是由ajax请求服务器得到的,所以我们要用的是ajax请求服务器的url。并且返回的职位信息是json格式数据)

import requests

url = 'https://www.lagou.com/jobs/positionAjax.json?city=%E6%9D%AD%E5%B7%9E&needAddtionalResult=false'

data = {'first': 'true','pn': 1,'kd': 'python'}

headers = {
    'Host': 'www.lagou.com',
    'Origin': 'https://www.lagou.com',
    'Referer': 'https://www.lagou.com/jobs/list_python?city=%E6%9D%AD%E5%B7%9E&cl=false&fromSearch=true&labelWords=&suginput=',
    'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36",
}

response = requests.post(url,data=data,headers=headers)

print(response.content.decode('utf-8'))
print(response.json())

如果返回的是json数据,可以直接调用response.json()来将json字符串转换为字典或者列表

使用代理

使用requests添加代理也非常简单,只要在请求的方法中(比如get或者post)传递proxies参数就可以了。示例代码如下:

import requests

url = 'http://httpbin.org/get'

headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36"}

proxy = {'http':"123.57.207.2:3128"}

resp = requests.get(url,headers=headers,proxies=proxy)

print(resp.content)

cookie

如果在一个响应中包含了cookie,那么我们利用cookie属性拿到这个返回的cookie值:

import requests

response = requests.get('http://www.baidu.com')
print(response.cookies)
print(response.cookies.get_dict())

打印结果:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
{'BDORZ': '27315'}

session

之前使用urllib库,是可以使用opener发送多个请求,多个请求之间可以共享cookie的。那么如果使用requests,也要达到共享cookie的目的,那么可以使用requests库给我们提供的session对象,该对象封装了获取到的cookie信息。注意这里的session不是web开发中的那个session,这个地方只是一个会话对象而已。还是以登录人人网为例,使用requests来实现。示例代码如下:

import requests

url = 'http://www.renren.com/PLogin.do'
data = {'email':'xxx@qq.com','password':'yyyy'}

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36'}

# 登录
session = requests.session()
session.port(url,data=data,headers=headers)

# f访问他人个人中心
resp = session.get('http://www.renren.com/880151247/profile')
print(resp.text)

处理不信任的SSL证书

对于那些已经被信任的SSL证书的网站,比如https://www.baidu.com,那么使用requests直接就可以正常的返回响应。示例代码如下:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。