当前第2页 返回上一页
在 HTTP Request 中加入特定的 Header,来构造一个完整的HTTP请求消息。
可以通过调用Request.add_header() 添加/修改一个特定的header 也可以通过调用Request.get_header()来查看已有的header。
添加一个特定的header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # urllib2_headers.py
import urllib2
url = "http://www.itcast.cn"
#IE 9.0 的 User-Agent
header = { "User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;" }
request = urllib2.Request(url, headers = header)
#也可以通过调用Request.add_header() 添加/修改一个特定的header
request.add_header( "Connection" , "keep-alive" )
# 也可以通过调用Request.get_header()来查看header信息
# request.get_header(header_name= "Connection" )
response = urllib2.urlopen(req)
print response.code #可以查看响应状态码
html = response.read()
print html
|
随机添加/修改User-Agent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | # urllib2_add_headers.py
import urllib2
import random
url = "http://www.itcast.cn"
ua_list = [
"Mozilla/5.0 (Windows NT 6.1; ) Apple.... " ,
"Mozilla/5.0 (X11; CrOS i686 2268.111.0)... " ,
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X.... " ,
"Mozilla/5.0 (Macintosh; Intel Mac OS... "
]
user_agent = random.choice(ua_list)
request = urllib2.Request(url)
#也可以通过调用Request.add_header() 添加/修改一个特定的header
request.add_header( "User-Agent" , user_agent)
# 第一个字母大写,后面的全部小写
request.get_header( "User-agent" )
response = urllib2.urlopen(req)
html = response.read()
print html
|
相关教程推荐:Python视频教程
以上就是Python如何安装urllib2库的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
认识Python对象自省机制
如何在一个表达式里合并两个字典
详解Python使用asyncio包处理并发的方法
Python入口函数是什么
Python如何安装http server
Python实现二叉堆与堆排序的代码实例
qPython3l怎么用
学习Python使用自定义钉钉机器人的示例代码
Python如何发送?Python发送email的三种方式介绍
Python循环函数
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何安装urllib2库