pythonhttps
⑴ python 爬取https的登录界面,怎么爬取成功,谢谢
之前写的一直没成功,原因是用的不是HTTPS相关的函数。这次仔细研究了一下,有几个需要注意的点,一个是POST模拟登陆的时候,header中的cookie值,不同的网站应该会有不同的要求;另一个是GET页面的时候,是需要加上POST得到的response中的set-cookie的。这样才能利用登陆的成功。
写完POST和GET页面后,顺便写了个简单的命令行实现。
importhttplib,urllib
importurllib2
importcookielib
importsys
file_text="build_change.txt"
resultTable=dict()
host='buuuuuuu.knight.com'
defLogin(username,password,csrf=''):
url='/login/'
values={
'username':username,
'password':password,
'next':'',
'csrfmiddlewaretoken':csrf,
}
headers={
'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(Khtml,likeGecko)Chrome/35.0.1916.114Safari/537.36',
'Content-Type':'application/x-www-form-urlencoded',
'Connection':'keep-alive',
'Cookie':'csrftoken=%s'%csrf,
'Referer':'https://buuuuuuu.knight.com/login/',
'Origin':'https://buuuuuuu.knight.com',
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
}
values=urllib.urlencode(values)
conn=httplib.HTTPSConnection(host,443)
conn.request("POST",url,values,headers)
response=conn.getresponse()
print'Login:',response.status,response.reason
'''
hdata=response.getheaders()
foriinxrange(len(hdata)):
forjinxrange(len(hdata[i])):
printhdata[i][j],
'''
returnresponse.getheader("set-cookie")
defGetHtml(_url,cookie):
get_headers={
'Host':'xxxxx.knight.com',
'Connection':'keep-alive',
'Cache-Control':'max-age=0',
'Cookie':cookie,
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent':'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/35.0.1916.114Safari/537.36',
'Accept-Language':'zh-CN,zh;q=0.8,en;q=0.6',
}
conn=httplib.HTTPSConnection(host)
conn.request("GET",_url,None,get_headers)
res2=conn.getresponse()
print"Get%s:"%_url,res2.status,res2.reason
'''
hdata1=res2.getheaders()
foriinxrange(len(hdata1)):
forjinxrange(len(hdata1[i])):
printhdata1[i][j],
'''
data=res2.read()
fp=open("build_change.txt","w")
fp.write(data)
fp.close()
defParseHtml():
fp=open(file_text,"r")
content=fp.readline()
_pos=0
whilecontent:
ifcontent.find("class="change-body"")>=0:
topic=content.split(">")
resultTable[_pos]=topic[1]
whilecontent:
content=fp.readline()
resultTable[_pos]=resultTable[_pos]+content
ifcontent.find("</div>")>=0:
_pos=_pos+1
break
content=fp.readline()
fp.close()
print"Parsehtmlsuccess."
defGenerateResultTxt():
f=open("build_change_result.txt","w")
forminresultTable.keys():
f.write("------------------------------------------------------------------------------------------- ")
f.write(resultTable[m])
f.close()
print"Generateresultsuccess:build_change_result.txt."
defHelp():
print'-h:help'
print'-u:username(must)'
print'-p:password(must)'
print'-c:csrftoken(optional)'
print'-s:sandboxbuildid(must)'
print'Forexample:'
print'[1]pythonBuildChange.py-h'
print'[2]pythonBuildChang.py-uu-pp-ss1s2'
print'[3]pythonBuildChang.py-uu-pp-cc-ss1s2'
defParseParam(com):
length=len(com)
username=""
password=""
csrf=""
sid1=""
sid2=""
iflength==2orlength==8orlength==10:
ifcom[1]=='-h':
Help()
foriinrange(1,length):
ifcom[i]=='-u'andi<(length-1):
username=com[i+1]
i+=1
elifcom[i]=='-p'andi<(length-1):
password=com[i+1]
i+=1
elifcom[i]=='-c'andi<(length-1):
csrf=com[i+1]
i+=1
elifcom[i]=='-s'andi<(length-2):
sid1=com[i+1]
sid2=com[i+2]
i+=2
ifusername==""orpassword==""orsid1==""orsid2=="":
print'[Error]Parametererror!'
print'[Error]Youcanuse"pythonBuildChange.py-h"toseehowcanusethisscript.'
else:
ifcsrf=="":
cookie=Login(username,password)
else:
cookie=Login(username,password,csrf)
_url="//changelog//between//%s//and//%s/"%(sid1,sid2)
GetHtml(_url,cookie)
ParseHtml()
GenerateResultTxt()
#C:Python27python.exeC:UsersknightDesktopuildBuildChange.py-uxux-pKKKKKKKK-s18594091858525
if__name__=="__main__":
ParseParam(sys.argv)
⑵ python 获取当前页面的是http还是https
对象基本上就是一个字典把它转换成一个包含元组的列表,然后用合适的内分隔符连接起来就好了容12345importrequestsresp=requests.get(url)cookies=resp.cookiesprint(';'.join(['='.join(item)for
⑶ python如何用代理服务的方式获取https的请求和接受数据
你是在做webserver?
我测试没问题,你看看是不是防火墙什么的
⑷ 如何python中读取https传输中的cookie
在response的header里面,会有cookie的设置,response.headers['set-cookie']便可以看到
⑸ 如何 https python
用requests和urllib2报的错误信息是一样,可见它们都是基于相同的底层api操作的,比如基于TLS的socket连接。到这里的时候我怀疑这个问题不是python代码写的有问题,可能是操作系统级别的设置错了。
⑹ Python怎么抓https的包
https 是加密的包,你抓了也没用
⑺ Python登陆一个HTTPS网站时遇到问题
很多网站为了防止csrf,会在get某个网页上的form的时候,加入一个token在cookie或者在form的hidden field里面,然后在post的时专候属,检查有没有这个token。你看看是不是因为这个。
⑻ python请求https怎么搞
import requests
response=requests.get(httpsUrl,verify=False)
⑼ python requests怎么处理https加密数据
有时为了方便,在发送请求时把验SSL证书关掉, 设置verify为False,
import requests
from requests import Request, Session
for i in range (0,2):
s=requests.Session()
r1= s.get('httw..com/&', verify=False)
print r1
====
/usr/local/python-2.7/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:821: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
InsecureRequestWarning)
/usr/local/python-2.7/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:821: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
InsecureRequestWarning)
<Response [200]>
⑽ python 链接https安装什么软件
今天写代码时碰到一个问题,花了几个小时的时间google,
首先需要安装openssl,更新到最新版本后,在浏览器里看是否可访问,如果是可以的,所以应该不是openssl有问题。
然后使用 curl尝试访问
curl -v
可以查看ssl版本,如果不能访问,尝试更换ssl版本
1
2
3
4
5
curl
-1
curl
-2 h
curl
-3
分别用上面的三句脚本去测试连接情况,发现第三种可以连接正常(-1,2,3,数字分别代码tlsv1,sslv2,sslv3三个不同的SSL版本)。说明这个https连接所在的服务器是基于SSLV3版本的。找到的问题,就很容易知道怎么改写Python代码了。
1
2
3
4
5
6
7
8
9
class MyAdapter(HTTPAdapter):
def init_poolmanager(self,
connections, maxsize):
self.poolmanager
= PoolManager(num_pools=connections,
maxsize=maxsize,
ssl_version=ssl.PROTOCOL_SSLv3)
s
= requests.Session()
s.mount('https://',
MyAdapter())#所有的https连接都用ssl.PROTOCOL_SSLV3去连接
s.get('')
urllib2实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#
custom HTTPS opener, banner's oracle 10g server supports SSLv3 only
import httplib,
ssl, urllib2, socket
class HTTPSConnectionV3(httplib.HTTPSConnection):
def __init__(self,
*args,
**kwargs):
httplib.HTTPSConnection.__init__(self,
*args,
**kwargs)
def connect(self):
sock
= socket.create_connection((self.host,
self.port),
self.timeout)
if self._tunnel_host:
self.sock
= sock
self._tunnel()
try:
self.sock
= ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
ssl_version=ssl.PROTOCOL_SSLv3)
except ssl.SSLError,
e:
print("Trying
SSLv3.")
self.sock
= ssl.wrap_socket(sock,
self.key_file,
self.cert_file,
ssl_version=ssl.PROTOCOL_SSLv23)
class HTTPSHandlerV3(urllib2.HTTPSHandler):
def https_open(self,
req):
return self.do_open(HTTPSConnectionV3,
req)
#
install opener
urllib2.install_opener(urllib2.build_opener(HTTPSHandlerV3()))
if __name__
== "__main__":
r
= urllib2.urlopen("https://ui2web1.apps.uillinois.e/BANPROD1/bwskfcls.P_GetCrse")
print(r.read())
可以看到这两种方案的原理都是一样,就是自定义连接处理器,改变连接时ssl的版本号。