requests库本质上就是模拟了我们用浏览器打开一个网页,发起请求是的动作。它能够迅速的把请求的html源文
件保存到本地。
$ pip install requests
简单又粗暴,可以使用一下语句查看安装情况:
$ pip list
密密麻麻中发现了它,requests (2.14.2)
接下来,使用requests进行一个简单的操作,访问百度的index页面,并将其源码抓取出来,保存到r变量进行输出
注意这里的网页要补全http://,也就是你可以直接在网页内复制网页格式就可以。
使用ipython语句进行简单的操作,如若要写.py文件,则用vim即可。
In [1]: import requests
In [2]: r = requests.get("http://www.baidu.com")
In [3]: print(r.text)
输出结果是一堆网页的源码文件。我们使用requests库的get操作,他接受一个url参数并返回一个HTTP response对象。
requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求
具体requests库详解,请看 Python-第三方库requests详解或者官方版本
requests.get---
#这个方法可以接收三个参数,其中第二个默认为None 第三个可选
def get(url, params=None, **kwargs)
#作用是模拟发起GET请求
Sends a GET request.
#模拟获取页面的url链接
:param url: URL for the new :class:Request object.
#额外参数 字典或字节流格式,可选
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:Request.
# 十二个控制访问参数,比如可以自定义header
:param **kwargs: Optional arguments that request takes.
# 返回一个Response对象
:return: :class:Response <Response> object
:type: requests.Response
“**kwargs"参数:
params : 字典或字节序列,作为参数增加到url中 data : 字典、字节序列或文件对象,作为Request的内容 json : JSON格式的数据,作为Request的内容 headers : 字典,HTTP定制头 cookies : 字典或CookieJar,Request中的cookie auth : 元组,支持HTTP认证功能 files : 字典类型,传输文件 timeout : 设定超时时间,秒为单位 proxies : 字典类型,设定访问代理服务器,可以增加登录认证 allow_redirects : True/False,默认为True,重定向开关 stream : True/False,默认为True,获取内容立即下载开关 verify : True/False,默认为True,认证SSL证书开关 cert : 本地SSL证书路径 url: 拟更新页面的url链接 data: 字典、字节序列或文件,Request的内容 json: JSON格式的数据,Request的内容
常用的两个控制访问参数:headers+proxies
实例1:假设我们在GET请求里定义一个headers文件
>>> import requests
>>> hd = {'User-Agent':'123'}
>>> r = requests.get('http://www.baidu.com', headers = hd)
>>> print(r.requests.headers)
>>> print(r.request.headers)
{'User-Agent': '123', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
实例2:假设我们要定义一个代理池
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://www.baidu.com", proxies=proxies)
如果代理需要账户和密码,则需这样:
proxies = {
"http": "http://user:pass@10.10.1.10:3128/",
}
这里的可以通过ip测试网站进行验证是否成功使用了代理 http://ip.chinaz.com/(查看你访问后的网站的您的IP是多少来判断)python中requests使用代理proxies
#HTTP请求的返回状态,比如,200表示成功,404表示失败
print (r.status_code)
#HTTP请求中的headers
print (r.headers)
#从header中猜测的响应的内容编码方式
print (r.encoding)
#从内容中分析的编码方式(慢)
print (r.apparent_encoding)
#响应内容的二进制形式
print (r.content)
requests抓取网页的通用框架:
import requests
def getHtmlText(url):
try:
r = requests.get(url, timeout=30)
# 如果状态码不是200 则应发HTTOError异常
r.raise_for_status()
# 设置正确的编码方式
r.encoding = r.apparent_encoding()
return r.text
except:
return "Something Wrong!"
timeout=30(单位:S)
requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。
timeout 仅对连接过程有效,与响应体的下载无关。
timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常
(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)
r.encoding = r.apparent_encoding()
使用apparent_encoding可以获得真实编码,并进行字符集编码转换encoding得到正确的字符
声明:以下链接是文章原作者的相关链接!
每天的学习记录都会 同步更新到: 微信公众号: findyourownway 知乎专栏:https://zhuanlan.zhihu.com/Ehco-python blog : www.ehcoblog.ml