上一次写如何给QQ钓鱼网站提交数据时,提供了一个GetWeb函数,哪个函数可以get数据也能post数据。但是,如果是一系列操作,操作中需要cooke支持,哪个函数就不方便了。
因此,给出一个更新版
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
from urllib2 import URLError
ExploereHEADERS = {"Content-type": "application/x-www-form-urlencoded",
'Accept-Language':'zh-CN,zh;q=0.8',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0;Windows NT 5.0)',
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection": "close",
"Cache-Control": "no-cache"}
#设置cookie
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# 安装cookie
urllib2.install_opener(opener)
def GetWeb(url,values,method ='get'):
data = urllib.urlencode(values) #数据编码
if method == 'get':
url = url+'?'+data
req = urllib2.Request(url, headers = ExploereHEADERS)
else:
req = urllib2.Request(url, data,headers = ExploereHEADERS)
response = urllib2.urlopen(req)
the_page = response.read()
response.close() #不用了就关闭掉
return the_page;
另附,从网站下载图像
urllib.urlretrieve('http://xxxx.xxx.xxx/verifycode.jsp','temp1.jpg')
当然,如果也需要cookie支持
那么可用下面这个
def GetImage(url,name):
im = GetWeb(url,'')
f = open(name,'wb')
f.write(im)
f.close()
return ;