发现学习Python的小伙伴都是从“爬虫”入坑的,这里就分享一篇爬虫技术常用的Requests库的文章。来自Requests库的发明者Kenneth Reitz。
曾几何时,制作网络爬虫需要先导入“urllib”库,然后再进行各种套用,繁琐而复杂。现在介绍神奇的"requests"库,用大神Matt DeBoard的话说就是:“I’m going to get Kenneth Reitz’s Python requests module tattooed on my body, somehow. The whole thing.”
# -*- coding: utf-8 -*-
#Requests模块使用介绍
#第一部分:发出请求
import requests
r = requests.get('https://www.baidu.com') #使用requests模块的get函数获取网址,返回一个Response对象
#各种不同的http请求格式
r = requests.get('url') #get请求
r = requests.post('url', data = {'key':'value'}) #post请求
r = requests.delete('url') #delete请求
r= requests.head('url') #head请求
r = requests.options('url') #options请求
#第二部分:在URL中传递参数
payload = {'key1':'value1', 'key2':['value2','value3']}
r = requests.get('http://www.baidu.com', params=payload) #使用params关键字参数将这些参数作为字典值提供
print(r.url) #打印已编码好的URL
#第三部分:响应内容
r.encoding #查看返回的请求对象的编码,也可以修改编码形式
r.text #文本编码
r.content #为了方便HTML和XML可以在编码中查找制定内容,使用-content查看编码
#第四部分:二进制响应内容
r.content #对于非文本请求,以字节为单位响应正文
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content)) #从请求返回的二进制数据创建映像
#第五部分:JSON响应内容
r = requests.get('url')
r.json() #处理json数据
r.raise_for_status 或者 r.status_code #用来检查是否响应成功
#第六部分:响应原始内容
r = requests.get('url', stream = True)
r.raw
r.raw.read(10)
#自定义标题
headers = {'user-agent':'my-app/0.1'}
r = requests.get(url, headers = headers) #指定的headers=设置将覆盖原设置
r.headers #查看服务器的响应头
r.headers['Content-Type'] #访问特定头信息
#Cookie相关
r.cookies['example_cookie_name'] #访问响应的cookie
cookies = dict(cookie_are='working')
r = requests.get(url, cookies=cookies) #将自己的cookie发送到服务器
#第七部分:其他内容
r = request.head('url', allow_redirects=True) #允许重定义
r = request.get('url', timeout=0.001) #超时设置