所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。 在Python中有很多库可以用来抓取网页,我们先学习urllib2。 urllib2在 python3.x 中被改为urllib.request 1.urlopen 一、get请求#coding=utf-8 #python3urllib2变成urllib.request importurllib.request deftest(): url=urllib.request.urlopen('http://www.baidu.com') html=url.read() print(html.decode('utf-8'))
if__name__=='__main__': test() 2.Request 在我们第一个例子里,urlopen()的参数就是一个url地址; 但是如果需要执行更复杂的操作,比如增加HTTP报头,必须创建一个 Request 实例来作为urlopen()的参数;而需要访问的url地址则作为 Request 实例的参数。#coding=utf-8 #python3urllib2变成urllib.request importurllib.request deftest(): request=urllib.request.Request('http://www.baidu.com') url=urllib.request.urlopen(request) html=url.read() print(html.decode('utf-8'))
if__name__=='__main__': test() 3.User-Agent 但是这样直接用urllib2给一个网站发送请求的话,确实略有些唐突了,就好比,人家每家都有门,你以一个路人的身份直接闯进去显然不是很礼貌。而且有一些站点不喜欢被程序(非人为访问)访问,有可能会拒绝你的访问请求。 但是如果我们用一个合法的身份去请求别人网站,显然人家就是欢迎的,所以我们就应该给我们的这个代码加上一个身份,就是所谓的User-Agent头。
#coding=utf-8 #python3urllib2变成urllib.request importurllib.request deftest(): url='http://www.baidu.com' headers={"User-Agent":"Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0;"} request=urllib.request.Request(url,headers=headers) url=urllib.request.urlopen(request) html=url.read() print(html.decode('utf-8')) if__name__=='__main__': test() 添加更多的Header信息 在 HTTP Request 中加入特定的 Header,来构造一个完整的HTTP请求消息。 可以通过调用Request.add_header()添加/修改一个特定的header 也可以通过调用Request.get_header()来查看已有的header。
#coding=utf-8 #python3urllib2变成urllib.request importurllib.request deftest(): url='http://www.baidu.com' headers={"User-Agent":"Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Trident/5.0;"} request=urllib.request.Request(url,headers=headers) request.add_header('Connection','keep-alive') response=urllib.request.urlopen(request) print(response.code) html=response.read() print(html.decode('utf-8'))
if__name__=='__main__': test() 随机添加/修改User-Agent #coding=utf-8 #python3urllib2变成urllib.request importurllib.request importrandom deftest(): url='http://www.baidu.com' ua_list=[ "Mozilla/5.0(WindowsNT6.1;)Apple....", "Mozilla/5.0(X11;CrOSi6862268.111.0)...", "Mozilla/5.0(Macintosh;U;PPCMacOSX....", "Mozilla/5.0(Macintosh;IntelMacOS..." ] user_agent=random.choice(ua_list) request=urllib.request.Request(url) request.add_header('User-Agent',user_agent) request.get_header('User-agent') response=urllib.request.urlopen(request) print(response.code) html=response.read() print(html.decode('utf-8'))
if__name__=='__main__': test() |
|
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除
|