我正在练习“使用Python进行网络抓取”的代码,我一直有这个证书问题:

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import re

pages = set()
def getLinks(pageUrl):
    global pages
    html = urlopen("http://en.wikipedia.org"+pageUrl)
    bsObj = BeautifulSoup(html)
    for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
        if 'href' in link.attrs:
            if link.attrs['href'] not in pages:
                #We have encountered a new page
                newPage = link.attrs['href'] 
                print(newPage) 
                pages.add(newPage) 
                getLinks(newPage)
getLinks("")

错误是:

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1319, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1049)>

顺便说一句,我也在练习scrapy,但一直得到的问题:命令找不到:scrapy(我尝试了各种在线解决方案,但没有一个工作…真的令人沮丧)


当前回答

这是可行的。将环境变量pythonhttpverify设置为0。

输入linux命令:

export PYTHONHTTPSVERIFY = 0

OR

使用python代码:

import os
os.environ["PYTHONHTTPSVERIFY"] = "0"

其他回答

遗憾的是,我没有解决这个问题。 但设法使代码工作(顺便说一句,几乎所有我的代码都有这个问题) 本地颁发者证书问题发生在python3.7下 所以我改回python2.7 QAQ 所有这些都需要改变,包括“from urllib2 import urlopen”而不是“from urllib”。请求导入urlopen" 如此悲伤…

使用请求库。 试试这个解决方案,或者只是在URL前添加https://:

import requests
from bs4 import BeautifulSoup
import re

pages = set()
def getLinks(pageUrl):
    global pages
    html = requests.get("http://en.wikipedia.org"+pageUrl, verify=False).text
    bsObj = BeautifulSoup(html)
    for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
        if 'href' in link.attrs:
            if link.attrs['href'] not in pages:
                #We have encountered a new page
                newPage = link.attrs['href']
                print(newPage)
                pages.add(newPage)
                getLinks(newPage)
getLinks("")

检查一下这对你是否有效

看看这篇文章,似乎对于Python的后期版本,证书没有预安装,这似乎导致了这个错误。您应该能够运行以下命令来安装证书包:/Applications/Python\ 3.6/ install \ Certificates.command

Post 1: urllib和“SSL: CERTIFICATE_VERIFY_FAILED”错误

帖子2:Airbrake错误:urlopen错误[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:无法获得本地颁发者证书

如果你在Mac上运行,你可以在聚光灯下搜索Install Certificates.command,然后按enter键。

终端命令:

打开/Applications/Python\ 3.7/Install\ Certificates.command

在这里找到: https://stackoverflow.com/a/57614113/6207266

帮我解决了。 用我的配置

PIP安装——升级证书

没有影响。