python请求会话的SSL错误

时间:2018-02-11 02:51:51

标签: python ssl python-requests urllib

我想问你一些帮忙。我正在尝试从python登录源代码解决ssl错误,但仍然不知道如何解决这个问题。

■环境

Python 3.5.2

请求 - 最新版本

■源代码

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

# login username and password
USER = "JS-TESTER"
PASS = "ipCU12ySxI"

# session starts
session = requests.session()

# login information
login_info = {
    "username_mmlbbs6": USER,  
    "password_mmlbbs6": PASS,  
    "back": "index.php",       
    "mml_id": "0"             
}
url_login = "http://uta.pw/sakusibbs/users.php?action=login&m=try"
res = session.post(url_login, data=login_info)
res.raise_for_status() 

# pick up mypage's url
soup = BeautifulSoup(res.text, "html.parser")
a = soup.select_one(".islogin a")
if a is None:
    print("Couldn't load mypage data")
    quit()
# Convert the relative URL to an absolute URL
url_mypage = urljoin(url_login, a.attrs["href"])
print("マイページ=", url_mypage)

# Access mypage
res = session.get(url_mypage)
res.raise_for_status()

# List up favorite titles
soup = BeautifulSoup(res.text, "html.parser")
links = soup.select("#favlist li > a")
for a in links:
    href = a.attrs["href"]
    title = a.get_text()
    print("-", title, ">", href)

■错误详情

[vagrant@localhost ch2]$ python login-getfav.py
Traceback (most recent call last):
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/contrib/pyopenssl.py", line 441, in wrap_socket
cnx.do_handshake()
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1806, in do_handshake
self._raise_ssl_error(self._ssl, result)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1546, in _raise_ssl_error
_raise_current_error()
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/OpenSSL/_util.py", line 54, in exception_from_error_queue
raise exception_type(errors)
OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connectionpool.py", line 346, in _make_request
self._validate_conn(conn)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connectionpool.py", line 850, in validate_conn
conn.connect()
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connection.py", line 326, in connect
ssl_context=context)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/util/ssl.py", line 329, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/contrib/pyopenssl.py", line 448, in wrap_socket
raise ssl.SSLError('bad handshake: %r' % e)
ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/util/retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='uta.pw', port=443): Max retries exceeded with url: /sakusibbs/users.php?action=login&m=try (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "login-getfav.py", line 21, in 
res = session.post(url_login, data=login_info)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 555, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 640, in send
history = [resp for resp in gen] if allow_redirects else []
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 640, in 
history = [resp for resp in gen] if allow_redirects else []
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 218, in resolve_redirects
**adapter_kwargs
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/requests/adapters.py", line 506, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='uta.pw', port=443): Max retries exceeded with url: /sakusibbs/users.php?action=login&m=try (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

■假设

在其他源代码中,我尝试更改请求get方法如下(verify = False)并且它有效。我想知道我是否也可以将它应用于会话方法呢?是这样,我应该把verify = False ...

放在哪里
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

# login username and password
USER = "JS-TESTER"
PASS = "ipCU12ySxI"

# session starts
session = requests.session()

# login information
login_info = {
    "username_mmlbbs6": USER,  
    "password_mmlbbs6": PASS,  
    "back": "index.php",       
    "mml_id": "0"             
}
url_login = "http://uta.pw/sakusibbs/users.php?action=login&m=try"
res = session.post(url_login, data=login_info, verify=False)
res.raise_for_status() 

# pick up mypage's url
soup = BeautifulSoup(res.text, "html.parser")
a = soup.select_one(".islogin a")
if a is None:
    print("Couldn't load mypage data")
    quit()
# Convert the relative URL to an absolute URL
url_mypage = urljoin(url_login, a.attrs["href"])
print("マイページ=", url_mypage)

# Access mypage
res = session.get(url_mypage)
res.raise_for_status()

# List up favorite titles
soup = BeautifulSoup(res.text, "html.parser")
links = soup.select("#favlist li > a")
for a in links:
    href = a.attrs["href"]
    title = a.get_text()
    print("-", title, ">", href)

■错误明细

[vagrant@localhost ch2]$ python login-getfav.py
/home/vagrant/.pyenv/versions/3.5.2/lib/python3.5/site-packages/urllib3/connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
Couldn't load mypage data

0 个答案:

没有答案