爬虫入门学习

在python3中将urllib3重构后变为urllib.requesr使用,网页在抓取之后要指定decode解码。

通常为了通过服务器的检测,会更改请求头的部分数据,以伪装成浏览器来访问。

此时User-Agent,设置为浏览器模式尤为重要,尽量不要设置支持gzip压缩方式接收数据

 1 import urllib.request
 2 
 3 url="http://www.hao123.com/"
 4 ua_headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"}
 5 
 6 # 构造一个待访问链接对象
 7 request=urllib.request.Request(url=url,headers=ua_headers)
 8 # 构造一个请求访问对象
 9 response=urllib.request.urlopen(request)
10 
11 html=response.read()
12 
13 print(html.decode("utf-8"))
14 
15 print(response.getcode(),response.geturl())

猜你喜欢

转载自www.cnblogs.com/wen-kang/p/10417621.html