http://blog.sina.com.cn/s/blog_74a7e56e010177l8.html
#!usr/bin/env python
#-*- coding: utf-8 -*-
import os
import urllib2
import urllib
import cookielib
import xml.etree.ElementTree as ET
#-----------------------------------------------------------------------------
# Login in www.***.com.cn
def ChinaBiddingLogin(url, username, password):
# Enable cookie support for urllib2
cookiejar=cookielib.CookieJar()
urlopener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(urlopener)
urlopener.addheaders.append(('Referer', 'http://www.chinabidding.com.cn/zbw/login/login.jsp'))
urlopener.addheaders.append(('Accept-Language', 'zh-CN'))
urlopener.addheaders.append(('Host', 'www.chinabidding.com.cn'))
urlopener.addheaders.append(('User-Agent', 'Mozilla/5.0 (compatible; MISE 9.0; Windows NT 6.1); Trident/5.0'))
urlopener.addheaders.append(('Connection', 'Keep-Alive'))
print 'XXX Login......'
imgurl=r'http://www.*****.com.cn/zbw/login/image.jsp'
DownloadFile(imgurl, urlopener)
authcode=raw_input('Please enter the authcode:')
#authcode=VerifyingCodeRecognization(r"http://192.168.0.106/images/code.jpg")
# Send login/password to the site and get the session cookie
values={'login_id':username, 'opl':'op_login', 'login_passwd':password, 'login_check':authcode}
urlcontent=urlopener.open(urllib2.Request(url, urllib.urlencode(values)))
page=urlcontent.read(500000)
# Make sure we are logged in, check the returned page content
if page.find('login.jsp')!=-1:
print 'Login failed with username=%s, password=%s and authcode=%s' \
% (username, password, authcode)
return False
else:
print 'Login succeeded!'
return True
#-----------------------------------------------------------------------------
# Download from fileUrl then save to fileToSave
# Note: the fileUrl must be a valid file
def DownloadFile(fileUrl, urlopener):
isDownOk=False
try:
if fileUrl:
outfile=open(r'/var/www/images/code.jpg', 'w')
outfile.write(urlopener.open(urllib2.Request(fileUrl)).read())
outfile.close()
isDownOK=True
else:
print 'ERROR: fileUrl is NULL!'
except:
isDownOK=False
return isDownOK
#------------------------------------------------------------------------------
# Verifying code recoginization
def VerifyingCodeRecognization(imgurl):
url=r'http://192.168.0.119:800/api?'
user='admin'
pwd='admin'
model='ocr'
ocrfile='cbi'
values={'user':user, 'pwd':pwd, 'model':model, 'ocrfile':ocrfile, 'imgurl':imgurl}
data=urllib.urlencode(values)
try:
url+=data
urlcontent=urllib2.urlopen(url)
except IOError:
print '***ERROR: invalid URL (%s)' % url
page=urlcontent.read(500000)
# Parse the xml data and get the verifying code
root=ET.fromstring(page)
node_find=root.find('AddField')
authcode=node_find.attrib['data']
return authcode
#------------------------------------------------------------------------------
# Read users from configure file
def ReadUsersFromFile(filename):
users={}
for eachLine in open(filename, 'r'):
info=[w for w in eachLine.strip().split()]
if len(info)==2:
users[info[0]]=info[1]
return users
#------------------------------------------------------------------------------
def main():
login_page=r'http://www.***.com.cnlogin/login.jsp'
download_page=r'http://www.***.com.cn***/***?record_id='
start_id=8593330
end_id=8595000
now_id=start_id
Users=ReadUsersFromFile('users.conf')
while True:
for key in Users:
if ChinaBiddingLogin(login_page, key, Users[key]):
for i in range(3):
pageUrl=download_page+'%d' % now_id
urlcontent=urllib2.urlopen(pageUrl)
filepath='./download/%s.html' % now_id
f=open(filepath, 'w')
f.write(urlcontent.read(500000))
f.close()
now_id+=1
else:
continue
#------------------------------------------------------------------------------
if __name__=='__main__':
main()
python登陆网页并处理网站session和cookie
import cookielib, urllib, urllib2
login = 'ismellbacon123@yahoo.com'
password = 'login'
# Enable cookie support for urllib2
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
# Send login/password to the site and get the session cookie
values = {'login':login, 'password':password }
data = urllib.urlencode(values)
request = urllib2.Request("http://www.imdb.com/register/login", data)
url = urlOpener.open(request) # Our cookiejar automatically receives the cookies
page = url.read(500000)
# Make sure we are logged in by checking the presence of the cookie "id".
# (which is the cookie containing the session identifier.)
if not 'id' in [cookie.name for cookie in cookiejar]:
raise ValueError, "Login failed with login=%s, password=%s" % (login,password)
print "We are logged in !"
# Make another request with our session cookie
# (Our urlOpener automatically uses cookies from our cookiejar)
url = urlOpener.open('http://imdb.com/find?s=all&q=grave')
page = url.read(200000)
如果你还在为python的各种urllib和urlibs,cookielib 头疼,或者还还在为python模拟登录和抓取数据而抓狂,那么来看看我们推荐的requests,python采集数据模拟登录必备利器!
这也是python推荐的HTTP客户端库:
本文就以一个模拟登录的例子来加以说明,至于采集大家就请自行发挥吧。
代码很简单,主要是展现python的requests库的简单至极,代码如下:
s = requests.session()
data = {'user':'用户名','passdw':'密码'}
#post 换成登录的地址,
res=s.post('http://www.xxx.net/index.php?action=login',data);
#换成抓取的地址
s.get('http://www.xxx.net/archives/155/');
有几种方法。一种是设置环境变量http_proxy,它会自动访问这个。 另外一种是你使用urllib2的时候,在参数里加上代理。还有一个是urllib上指定。
比如
import urllib
urllib.urlopen(某网站,proxyes={'http:':"某代理IP地址:代理的端口"})
proxy_handle = urllib.request.ProxyHandler({'http':random.choice(proxy_list)})
opener = urllib.request.build_opener(proxy_handle)
response = opener.open(url)
实验室使用代理上网,因此如果使用Python写程序访问网络的话就必须设置代理。
Python3将urllib和urllib2合二为一,而且重组了下包结构。网上很多的代码都是Python2的,所以自己看了下文档。
但是问题还是有的,根据http://markmail.org/thread/vzegucz53ouwykz4#query:+page:1+mid:2pluljbacgfwte3j+state:results中所述,urllib2 只支持 HTTP_GET 的代理,而CCProxy只支持HTTP_Connect的代理,因此如果上网的话就不能使用CCProxy作为代理了。
import urllib.request
proxy_handler = urllib.request.ProxyHandler({'http':'123.123.2123.123:8080'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', '123.123.2123.123', 'user', 'password')
opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler)
f = opener.open('http://www.baidu.com')
a = f.read()