Urllib 库是 Python 中的一个功能强大、用于操作 URL,并在做爬虫的时候经常要用到的库,在Python2 中,分 Urllib 库和 Urllib2 库,Python3 之后合并到 Urllib 库。
在python3后,都自带urllib模块,接下来,简单说一下如何运用urllib进行页面数据获取
urlopen()函数:
import urllib.request#导入urllib模块
response = urllib.request.urlopen("http://www.baidu.com")#直接打开一个网站
print(response.read().decode('utf-8'))#对获取到的网页源码进行utf-8解码
运行结果(结果很长,这里就不全部截图了):
超时处理:当网速不好,或者对方发现你是一个爬虫后对你请求拒绝,防止程序卡死在这里或者被网站封杀ip
import urllib.request
try:
response=urllib.request.urlopen("http://www.baidu.com",timeout=0.1)#进行超时处理,防止程序卡死
print(response.read().decode("utf-8"))
except urllib.error.URLError as a:
print("time out!")
这里运用了异常处理,使程序更加稳定和健壮
当我们运用urlopen()函数直接访问网页获取数据时,很可能遇见418这个错误,如下面代码
try:
response=urllib.request.urlopen("http://douban.com")#申请访问豆瓣
print(response.read().decode("utf-8"))
except IndentationError as a:
print(a)
运行结果:
可以看到出现了错误418,这是因为对方已经识别出了你是一个爬虫,从而拒绝了你的请求,这时候我们需要用到**Request()**这个方法,通过向里面添加headers进行伪装
import urllib.request
url="https://douban.com"
#模拟浏览器头部信息,向豆瓣服务器发送消息
headers={
"USer-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
#用户代理,表示告诉服务器,我们是浏览器访问(本质上是告诉浏览器,我们可以接受什么水平的文件)
}
req=urllib.request.Request(url=url,headers=headers)#用Request类构建了一个完整的请求,增加了headers等一些信息
response=urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
当我们进行伪装后仍然出现了418或者403的情况我们通过useragent轮换,添加cookies值,将访问时间间隔设长一点等方法尝试,如
import urllib.request
from random import choice
import random
#导入所需要的模块
url="http://douban.com"
user_agent=[
"Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 95.0.4638.54Safari / 537.36",
"Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0",
"Opera/9.80(WindowsNT6.1;U;en)Presto/2.8.131Version/11.11",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
]
head={
#模拟浏览器头部信息,向豆瓣服务器发送消息
"User - Agent": choice(user_agent)#在user_agent中任意选择一个用户代理
}
#用户代理,表示告诉服务器,我们是浏览器访问(本质上是告诉浏览器,我们可以接受什么水平的文件)
req=urllib.request.Request(url=url,headers=head)
html=""
try:
response = urllib.request.urlopen(req,timeout=0.1)
html=response.read().decode("utf-8")
print(html)
except Exception as e:#判断e这个对象里面是否包含code这个属性
if hasattr(e,"code") : #hasattr用于判断对象是否包含某一属性
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
# time.sleep(random.random() * 3)#对页面进行大量频繁访问时可通过延长访问时间来模拟用户行为
urllib.parse,用于解析URL,类似于一个解析器:
# 获取一个post请求
import urllib.parse
Data = bytes(urllib.parse.urlencode({
"hello":"world"}),encoding="utf-8")#用utf-8将二进制bytes进行封装
response=urllib.request.urlopen("http://httpbin.org/post",data=Data)
print(response.read().decode("utf-8"))
运行结果:
可以看到发送成功了请求。
本篇文章简单的介绍了一下urllib库的使用,如有不妥还望包含