python如何访问网页

3,292次阅读
没有评论

使用Python访问网页主要有三种方式: urllib, urllib2, httplib

urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session

python如何访问网页

 最简单的页面访问

import urllib2
res=urllib2.urlopen(url)
except urllib2.URLError, e:
print res.read()

加上要get或post的数据

data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))

 加上http头

header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)#使用opener和handler
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

加上session

cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-11-29发表,共计605字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)