【发布时间】:2018-06-05 04:02:34
【问题描述】:
我正在参加 Coursera Course Python For Everyone 课程,我尝试了来自textbook 的问题之一:
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = 'https://www.py4e.com/book.htm'
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print(tag.get('href', None))
我不明白错误:
urllib.error.HTTPError: HTTP Error 403: Forbidden
但是根据完整的错误,它从@Line 18 开始。从阅读其他 SO 和这个Similar Question 来看,它可能与 SSL 证书以及网站如何认为我是机器人有关。 为什么代码不起作用?
【问题讨论】:
-
您可以在您的请求中add a header
标签: python-3.x beautifulsoup ssl-certificate html-parsing urllib