python模拟登陆带验证码的网站
# Login in www.chinabidding.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', 'text/html, application/xhtml+xml, */*'))
#urlopener.addheaders.append(('Accept-Encoding', 'gzip, deflate'))
#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 'Login......'
imgurl=r'http://www.chinabidding.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, 'op1':'op_login', 'login_passwd':password, 'login_check':authcode}
data=urllib.urlencode(values)
urlcontent=urlopener.open(urllib2.Request(url, data))
print urlcontent.geturl()
# Make sure we are logged in
if not 'id' in [cookie.name for cookie in cookiejar]:
print "Login failed with login=%s, password=%s, authcode=%s" % (username, password, authcode)
print 'We are logged in!'
page=urlcontent.read(500000)
return page
# 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', 'wd')
outfile.write(urlopener.open(urllib2.Request(fileUrl)).read())
outfile.close()
isDownOK=True
else:
print 'ERROR: fileUrl is NULL!'
except:
isDownOK=False
return isDownOK