Python爬虫实践 —— urllib.request和requests

之前的两个demo使用的是urllib内的request模块,其中我们不免发现,返回体要获取有效信息,请求体拼接都需要decode或encode后再装载,http请求的话需要先构造get或post请求再调用,proxy和header等请求头需要先构造。而requests库帮我们进一步封装了request模块,我们只需要直接调用对应的request method方法,就可以方便地构造http请求。但是遇到模拟登陆等情况下时,使用urllib自定义定制http请求也是必不可少的。

比较一下urlib.request 和 requests的不同

首先是urllib.request

# demo_urllib
from urllib import request

headers = {
"User-Agent": "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36"
}
wd = {"wd": "中国"}
url = "http://www.baidu.com/s?"
req = request.Request(url, headers=headers)
response = request.urlopen(req)
print(type(response))
print(response)
res = response.read().decode()
print(type(res))
print(res)

结果:

urllib库的response对象是先创建httprequest对象,装载到reques.urlopen里完成http请求,返回的是httpresponse对象,实际上是html属性,使用.read().decode()解码后转化成了str字符串类型,也可以看到decode解码后中文字符能够显示出来

接着是reuqests

# demo_requests
import requests

headers = {
"User-Agent": "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36"
}
wd = {"wd": "中国"}
url = "http://www.baidu.com/s?"
response = requests.get(url, params=wd, headers=headers)
data = response.text
data2 = response.content
print(response)
print(type(response))
print(data)
print(type(data))
print(data2)
print(type(data2))
print(data2.decode())
print(type(data2.decode()))

结果:

requests库调用是requests.get方法传入url和参数,返回的对象是Response对象,打印出来是显示响应状态码,通过.text 方法可以返回是unicode 型的数据,一般是在网页的header中定义的编码形式,而content返回的是bytes,二级制型的数据,还有 .json方法也可以返回json字符串。如果想要提取文本就用text,但是如果你想要提取图片、文件等二进制文件,就要用content,当然decode之后,中文字符也会正常显示啦  >_<

原文地址:https://www.cnblogs.com/liuchaodada/p/12050745.html