當前位置:首頁 » 編程語言 » pythonsslhttps

pythonsslhttps

發布時間: 2023-05-12 07:17:53

『壹』 怎麼解決使用python的requests獲得網頁時出現sslEOFError錯誤

  • importrequests

  • url="httplogin.html"

  • ret=requests.get(url,verify="/Test/ssl_address/qlchat.com.crt")

  • printret.status_code

  • 通過 verify 指定證書,表示相信此證書(52.77.252.184.crt 是伺服器端證書);也可以用 verify=False,表示不驗證伺服器端的證書。

    https的證書獲取:

    通過Chrome裡面-設置-證書,可以導出該域名的ssl證書,然後放到指定路徑,verify=證書路徑。就能直接請求https了

『貳』 python requests請求ssl 加密 提示[SSL: CA_MD_TOO_WEAK] ca md too weak (_ssl.c:4024)')))

伺服器環境中的加密套件不支持這種加密方式。建議您升級一下加密套件版本到最新重新配置SSL。

『叄』 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的版本號。

『肆』 python 獲取https網站數據

一,檢查pip有沒安大模飢裝cryptography,pyOpenSSL,certifi

pip install cryptography

pip install pyOpenSSL

pip install certifi

二碼答,滾返添加ssl驗證

import ssl

ssl._create_default_https_context = ssl._create_stdlib_context

三,添加header

header = {

"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Safari/537.36 Edg/89.0.774.45"

}

四,調用requests的get介面

response = requests.get(url,headers=header)

content = response.text

print(content)

就能獲取到html內容,如果需要更好的解釋html標簽內容可以使用 BeautifulSoup

『伍』 python中的ssl error怎麼解決

python安裝完畢後,提示找不到ssl模塊:
[root@localhost ~]# python2.7.5
Python 2.7.5 (default, Jun 3 2013, 11:08:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "right", "credits" or "license" for more information.
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
File "/usr/local/python27/lib/python2.7/ssl.py", line 60, in <mole>
import _ssl # if we can't import it, let the error propagate
ImportError: No mole named _ssl
>>>
2. 查看openssl安裝包,發現缺少openssl-devel包
[root@localhost ~]# rpm -aq|grep openssl
openssl-0.9.8e-20.el5
openssl-0.9.8e-20.el5
[root@localhost ~]#
3. yum安裝openssl-devel
[root@localhost ~]# yum install openssl-devel -y
#查看安裝結果
[root@localhost ~]# rpm -aq|grep openssl
openssl-0.9.8e-26.el5_9.1
openssl-0.9.8e-26.el5_9.1
openssl-devel-0.9.8e-26.el5_9.1
openssl-devel-0.9.8e-26.el5_9.1
4. 重新編譯python
#修改Setup文件
vi /usr/software/Python-2.7.5/Moles/Setup
#修改結果如下:
# Socket mole helper for socket(2)
_socket socketmole.c timemole.c
# Socket mole helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto

5. 重新編譯
make
make install
6. 測試,已可正常使用。
[root@localhost ~]# python2.7.5
Python 2.7.5 (default, Jun 3 2013, 14:56:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "right", "credits" or "license" for more information.
>>> import ssl
>>>

『陸』 Python要求扔了sslerror問題,怎麼解決

我在使用requests訪問某個https網站時出現錯誤
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Session Objects會話對象

Session對象在請求時允許你堅持一定的參數。此外,還堅持由Session實例的所有請求的cookie。

讓我們堅持在請求時使用

s = requests.Session()

s.get('httpsokie/123456789')
r = s.get("httrg/cookies")

print r.text
# '{"cookies": {"sessioncookie":"123456789"}}'

會話也可以用於提供默認的數據的請求的方法。這是通過提供的數據會話對象的屬性:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('ht, headers={'x-test2': 'true'})

任何字典將被合並session級別的設置的值傳遞給請求方法。方法級別的參數覆蓋會話參數。

從一個字典參數中取值

如果你想在一個session中刪除一個參數,那麼你只需要設置它為none,他便自動被刪去。

在一個session中的所有值都包含直接提供給你。參閱Session API文檔了解更多信息。

請求和響應對象

>>> r = requests.get('hia.org/wiki/Monty_Python')

查看

>>> r.headers
{'content-length': '56170', 'x-content-type-options': 'nosniff','x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet','content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary':'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT fromcp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}

但是,如果我們想要得到我們的伺服器發送的報頭,我們只需訪問請求,然後請求標頭:

>>> r.request.headers
{'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}

准備請求

當你在API呼叫或會話呼叫收到一個Response對象,請求屬性實際上是PreparedRequest使用。在某些情況下,發送請求之前,你不妨做一些額外的工作,身體或頭(或任何其他真的)。這個簡單的配方如下:

from requests import Request, Session

s = Session()
prepped = Request('GET', # or any other method, 'POST', 'PUT', etc.
url,
data=data
headers=headers
# ...
).prepare()
# do something with prepped.body
# do something with prepped.headers
resp = s.send(prepped,
stream=stream,
verify=verify,
proxies=proxies,
cert=cert,
timeout=timeout,
# etc.
)
print(resp.status_code)

既然你沒有做什麼特別的請求對象,你准備立即修改的PreparedRequest的對象。然後,您可以發送您所要發送的請求的其他參數。*或Sesssion中。*。

SSL證書驗證

請求可以驗證SSL證書的HTTPS請求,就像一個網路瀏覽器。檢查主機的SSL證書,您可以使用校驗參數:

>>> requests.get('httpreitz.com', verify=True)
requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't matcheither of '*.herokuapp.com', 'herokuapp.com'

我沒有對這個域的SSL設置,所以它的失敗。好極了 Github上雖然沒有:

>>> requests.get('httpb.com', verify=True)
<Response [200]>

您也可以通過驗證一個私人證書CA_BUNDLE文件的路徑。您還可以設置環境變數的REQUESTS_CA_BUNDLE。

如果你設置驗證設置為False,也可以忽略驗證SSL證書。

>>> requests.get('httpethreitz.com',cert=('/path/server.crt', '/path/key'))
<Response [200]>

如果指定了錯誤的路徑或無效的證書:

>>> requests.get('htreitz.com',cert='/wrong_path/server.pem')
SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSLroutines:SSL_CTX_use_PrivateKey_file:PEM lib

主體內容工作流程

默認情況下,當你提出一個請求時,機體的反應是立即下載。您可以重寫此行為,並推遲下載響應的身體,直到您訪問Response.content,與流參數的屬性:

tarball_url = 'httnnethreitz/requests/tarball/master'
r = requests.get(tarball_url, stream=True)

僅在這一點上已下載的響應頭和連接保持打開狀態,從而使我們能夠使內容檢索條件:

if int(r.headers['content-length']) < TOO_LONG:
content = r.content
...

您可以進一步控制的使用的Response.iter_content和Response.iter_lines方法的工作流程,或從基本的urllib3 urllib3.HTTPResponse在Response.raw閱讀。

保持活動

需要注意的是發布的連接會回到池會重用所有以讀取的數據:
確保為設置數據流false或閱讀Response對象的內容屬性。

上傳

請求支持它允許你發送大量的沒有讀取到內存的流或文件流上傳,。要流和上傳,只需為你的身體提供了一個類似文件的對象:

with open('massive-body') as f:
requests.post('httpl/streamed', data=f)

塊編碼請求:

還請支持分塊傳輸編碼傳出和傳入的請求。要發送一個數據塊編碼的請求,只是提供一個生成器(或任何沒有長度的迭代器)為您的BODY:

def gen():
yield 'hi'
yield 'there'

requests.post('http:/chunked', data=gen())

事件鉤子:

請求有一個鉤子,系統,你可以用它來處理申請過程中的部分或信號事件的處理。

您可以指定一個鉤子函數在每個請求的基礎上,通過一個{hook_name:callback_function}字典的鉤請求參數:

hooks=dict(response=print_url)

那CALLBACK_FUNCTION將收到的數據塊作為第一個參數。

>>> requests.get('httbin.org',hooks=dict(response=print_url))
<Response [200]>

自定義身份驗證

這callback_function將收到一大塊的數據作為第一個參數。

from requests.auth import AuthBase

class PizzaAuth(AuthBase):
"""Attaches HTTP Pizza Authentication tothe given Request object."""
def __init__(self, username):
# setup any auth-related datahere
self.username = username

def __call__(self, r):
# modify and return the request
r.headers['X-Pizza'] =self.username
return r

Then, we can make a request using our Pizza Auth:

>>> requests.get('httrg/admin',auth=PizzaAuth('kenneth'))
<Response [200]>

代理

import requests

proxies = {
"http": "ht:3128",
"https": "htt0.1.10:1080",
}

requests.get("hple.org", proxies=proxies)

您還可以配置代理伺服器環境HTTP_PROXY and HTTPS_PROXY.

$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
$ python
>>> import requests
>>> requests.get("hple.org")

To use HTTP Basic Auth with your proxy, use the http://user:password@host/syntax:

proxies = {
"http":"[email protected]:3128/",
}

遵守:

要求是為了符合相關的規范和RFC的合規性,不會造成困難,為用戶。這受到關注,可能會導致一些看似尋常的行為,可能對那些不熟悉有關規范。

編碼:

如果沒有明確的字元集是在HTTP頭中的Content-Type頭中包含文本。在這種情況下,RFC 2616指定默認的字元集必須是ISO-8859-1

HTTP動詞

要求提供訪問幾乎是全方位的HTTP動詞:GET,OPTIONS,HEAD,POST,PUT,PATCH和DELETE。下面提供了詳細的例子,使用這些不同的動詞在請求中,使用GitHub的API。

>>> import requests
>>> r =requests.get('httcom/repos/kennethreitz/requests/git/commits/')

因此,GitHub的返回JSON。我們可以使用r.json的方法來解析為Python對象。

>>> commit_data = r.json()
>>> print commit_data.keys()
[u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']
>>> print commit_data[u'committer']
{u'date': u'2012-05-10T11:10:50-07:00', u'email': u'[email protected]',u'name': u'Kenneth Reitz'}
>>> print commit_data[u'message']
makin' history

請求可以很容易地使用各種形式的認證,包括很常見的基本身份驗證。

>>> from requests.auth import HTTPBasicAuth
>>> auth = HTTPBasicAuth('[email protected]','not_a_real_password')
>>> r = requests.post(url=url, data=body, auth=auth)
>>> r.status_code
201
>>> content = r.json()
>>> print content[u'body']
Sounds great! I'll get right on it.

『柒』 python環境設置ssl

爬取數據需要用python請求網路數據, https的加密實現依賴openssl

利用源碼直接安裝

安裝zlib庫

安裝openssl到 /usr/local/openssl 目錄,安裝之後,編譯

安裝結孝螞束後執行以下命令

進入/usr/local目錄下,執行以下命令

在/etc/ld.so.conf文件的最後面,添加如下內容:/usr/local/openssl/lib
然後執行以下命令

添加OPESSL的環境變數,在etc/的profile的最後一行,添加:

查看openssl版本

使用源碼按過於繁瑣,如果對軟體版本沒有特殊要求的話可以巧森埋使用yum命令安裝和更新,既方便又快捷

先看下ssl有沒有被引入

報錯是因為python沒有帶--with-ssl 選項編譯
修改Setup.dist文件 (把Setup這個不帶後綴的也一起改了)

修改結果如下:(去掉最後4行的注釋)

切到春春python文件夾

完成之後

沒有報錯, 大功告成

參考鏈接
ImportError: No mole named _ssl
linux上安裝Openssl步驟詳解

熱點內容
微信打開網頁繼續訪問 發布:2025-07-18 10:09:50 瀏覽:47
蔬菜解壓游戲大全 發布:2025-07-18 10:00:12 瀏覽:70
linuxand 發布:2025-07-18 09:48:27 瀏覽:725
為什麼安卓的app下載不了 發布:2025-07-18 09:47:45 瀏覽:178
如何用伺服器搭建網路 發布:2025-07-18 09:36:05 瀏覽:451
迷你世界電腦版怎麼改密碼 發布:2025-07-18 09:26:41 瀏覽:51
php創建目錄 發布:2025-07-18 09:26:17 瀏覽:659
為什麼手機游戲分ios和安卓端 發布:2025-07-18 09:22:17 瀏覽:140
android數據顯示 發布:2025-07-18 09:17:27 瀏覽:528
腳本精靈天天酷跑怎麼用 發布:2025-07-18 09:00:04 瀏覽:154