马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import requests
import re
r = requests.get('https://ssr1.scrape.center/')
pattern = re.compile(r'<h2.*?>(.*?)</h2>', re.S)
titles = re.findall(pattern, r.text)
print(titles)
输出:requests.exceptions.SSLError: HTTPSConnectionPool(host='ssr1.scrape.center', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))
from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener
from urllib.error import URLError
username = "admin"
password = 'admin'
url = 'https://ssr3.scrape.center/'
p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)
try:
result = opener.open(url)
html = result.read().decode('utf-8')
print(html)
except URLError as e:
print(e.reason)
输出:[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)
是我电脑出来什么问题吗?
本帖最后由 isdkz 于 2023-5-8 18:28 编辑
那个是机器人答的,它因为没有用 opener.open,而是用了 urlopen 所以认证失败
你之前的报错是因为证书问题,证书问题解决的话不必要像机器人回答的那个代码那么复杂
至于为什么会有证书问题,可能作者那个网站的证书过期了,又或者 python 库中没有相应的根证书
两行代码就可以了:from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener
from urllib.error import URLError
import ssl # 注意这里
ssl._create_default_https_context = ssl._create_unverified_context # 注意这里
username = "admin"
password = 'admin'
url = 'https://ssr3.scrape.center/'
p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)
try:
result = opener.open(url)
html = result.read().decode('utf-8')
print(html)
except URLError as e:
print(e.reason)
|