利用urllib2方便处理网页捉包
来源:互联网 发布:美瞳购买知乎 编辑:程序博客网 时间:2024/05/16 12:36
根据urllib2的文档封装一个类,可处理post提交数据、gzip解压缩、cookie自动处理、通过代理下载等常用功能:
class HttpUrllib():
def __init__(self, proxies):
self.headerItem = {}
self.dataItem = {}
self.opener = None
if proxies:
self.opener = urllib2.build_opener(urllib2.ProxyHandler(proxies), urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
else:
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def appendHeader(self, key, value):
self.headerItem[key] = value
print self.headerItem
def addData(self, key, values):
self.dataItem[key]= values
return self.dataItem
def fetchHtmlOnGet(self, url):
data = None
if self.dataItem:
data = urllib.urlencode(self.dataItem)
req = urllib2.Request(url, data, self.headerItem)
urlnet = self.opener.open(req)
htmlCode = urlnet.read()
encoding = urlnet.info().getheader('Content-Encoding')
if encoding:
if 'gzip' in encoding:
htmlCode = self.__ungzip(htmlCode)
urlnet.close()
return htmlCode
def __ungzip(self, content):
compressedstream = StringIO.StringIO(content)
new_content = gzip.GzipFile(fileobj = compressedstream).read()
return new_content
- 利用urllib2方便处理网页捉包
- Python 利用urllib2 lxml 抓取网页信息
- 利用urllib2通过指定的URL抓取网页内容
- Python 中利用urllib2简单实现网页抓取
- python2利用urllib2抓取中文网页乱码的问题
- urllib2抓取网页
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 一个北京软件工程师的反思
- srand,rand函数的使用注意事项
- 深入Mysql字符集设置
- uva 705 - Slash Maze
- 用 for/in 在 Java 5.0 中增强循环
- 利用urllib2方便处理网页捉包
- android PreferenceActivity
- Ubuntu 12.10 server 安装 Jenkins
- Android透明效果的实现
- URL集合
- 类对象及类成员函数作为函数参数的方法
- 开机出现“Disk I/O error”的故障解决
- 提高手机上网速度的方法
- 学习JavaScript的理由