【发布时间】:2021-05-20 16:42:21
【问题描述】:
我尝试使用 urllib 模块为每个人尝试使用示例表单书 python 来抓取 https://docs.python.org 但没有得到预期的输出,甚至书也没有解释这一切
这是代码
# search fo link values within URL input
import urllib.request, urllib.parse, urllib.error
import re
import ssl
# ignore ssl certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input("Enter- ")
html = urllib.request.urlopen(url, context = ctx).read()
links = re.findall(b'^href="(http[s]?://.*?)"',html)
for link in links:
print(link.decode())
输出
$ python3 urlregex.py
Enter- https://docs.python.org
假设的输出是
Enter - https://docs.python.org
https://docs.python.org/3/index.html
https://www.python.org/
https://docs.python.org/3.8/
https://docs.python.org/3.7/
https://docs.python.org/3.5/
https://docs.python.org/2.7/
https://www.python.org/doc/versions/
https://www.python.org/dev/peps/
https://wiki.python.org/moin/BeginnersGuide
https://wiki.python.org/moin/PythonBooks
https://www.python.org/doc/av/
https://www.python.org/
https://www.python.org/psf/donations/
http://sphinx.pocoo.org
【问题讨论】:
-
从模式中删除 ^ 应该可以修复它,使行变为
links = re.findall(b'href="(http[s]?://.*?)"',html)...或者将 ^ 替换为更严格的空格,并且可能是本书文本的意图。 (^ 是正则表达式中的特殊字符,所以在这里似乎不合适) -
非常感谢我对代码有点困惑,所以我使用它,它变得很乱
标签: python linux ssl web-scraping urllib