Python爬虫3-----浏览器伪装

1、浏览器伪装技术原理

当爬取CSDN博客时,会发现返回403,因为对方服务器会对爬虫进行屏蔽,故需伪装成浏览器才能爬取。浏览器伪装一般通过报头进行。

2、获取网页的报头

3、代码:

import urllib.request
url="https://blog.csdn.net/blogdevteam/article/details/80324831"
header=("User-Agent","https://blog.csdn.net/blogdevteam/article/details/80324831")
#build_opener可以添加报头信息
opener=urllib.request.build_opener()
#添加报头
opener.addheaders=[header]
data=opener.open(url).read()
'''
#如果用urlopen来打开网页获取数据,则采用install_opener函数
#urllib.request.install_opener(opener)
#data=urllib.request.urlopen(url).read().decode("utf-8","ignore")
print(data)
原文地址:https://www.cnblogs.com/Lee-yl/p/9045561.html