(以上r.text内容过长,自行删除了部分,看出编码效果即可)
requests库的异常
注意requests库有时会产生异常,比如网络连接错误、http错误异常、重定向异常、请求url超时异常等等。所以我们需要判断r.status_codes
是否是200,在这里我们怎么样去捕捉异常呢?
这里我们可以利用r.raise_for_status()
语句去捕捉异常,该语句在方法内部判断r.status_code是否等于200,如果不等于,则抛出异常。
于是在这里我们有一个爬取网页的通用代码框架:
try:
r=requests.get(url,timeout=30)#请求超时时间为30秒
r.raise_for_status()#如果状态不是200,则引发异常
r.encoding=r.apparent_encoding #配置编码
return r.text
except:
return"产生异常"
看代码:
>>> r=requests.head("http://httpbin.org/get")
>>>r.headers
{'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'}
>>>r.text
""
1、向url post一个字典:
>>> payload={"key1":"value1","key2":"value2"}
>>> r=requests.post("http://httpbin.org/post",data=payload)
>>> print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.150",
"url": "http://httpbin.org/post"
}
2、向url post 一个字符串,自动编码为data
>>>r=requests.post("http://httpbin.org/post",data='helloworld')
>>>print(r.text)
{
"args": {},
"data": "helloworld",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "10",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.150",
"url": "http://httpbin.org/post"
}
看代码:
>>> payload={"key1":"value1","key2":"value2"}
>>> r=requests.put("http://httpbin.org/put",data=payload)
>>> print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.197.153.150",
"url": "http://httpbin.org/put"
requests.patch和request.put类似。
两者不同的是:
当我们用patch时仅需要提交需要修改的字段。
而用put时,必须将20个字段一起提交到url,未提交字段将会被删除。
patch的好处是:节省网络带宽。
requests.request()支持其他所有的方法。 requests.request(method,url,**kwargs)
不需要对头部做任何修改,即可爬网页
import requests
url='http://item.jd.com/2967929.html'
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[:1000]) #部分信息
except:
print("失败")
该网页中对爬虫进行的爬取做了限制,因此我们需要伪装自己为浏览器发出的请求。
import requests
url='http://www.amazon.cn/gp/product/B01M8L5Z3Y'
try:
kv={'user_agent':'Mozilla/5.0'}
r=requests.get(url,headers=kv)#改变自己的请求数据
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[1000:2000]) #部分信息
except:
print("失败")
百度的关键字接口:
https://www.baidu.com/s?wd=keyword
import requests
keyword='python'
try:
kv={'wd':keyword}
r=requests.get('https://www.baidu.com/s',params=kv)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(len(r.text))
except:
print("失败")
import requests
import os
try:
url="http://baishi.baidu.com/watch/02167966440907275567.html"#图片地址
root="E:/pic/"
path=root+url.split("/")[-1]
if not os.path.exists(root): #目录不存在创建目录
os.mkdir(root)
if not os.path.exists(path): #文件不存在则下载
r=requests.get(url)
f=open(path,"wb")
f.write(r.content)
f.close()
print("文件下载成功")
else:
print("文件已经存在")
except:
print("获取失败")
小结
本文介绍requests库的基本应用,后面我会记录怎么从爬取的内容提取到我们需要的部分。