首页 > 解决方案 > 如何使用美丽的汤提取特定部分中的维基百科链接?

问题描述

我正在尝试提取维基百科页面https://en.wikipedia.org/wiki/Privacy_law的另见部分中的 URL 。

我尝试了以下代码:

url_req = "https://en.wikipedia.org/wiki/Privacy_law"
response = requests.get(url=url_req,)
soup = BeautifulSoup(response.content, 'html.parser')

snippet = soup.find_all('h2')
for headline in snippet:
    if re.findall('see.{0,5}also',str(headline),re.IGNORECASE):
        links = headline.findall('a')
print(links)

我能够找到正确的标题,但无法访问 URL。他们是在一个<div>特定的之后<h2>。如何获取这些 URL?

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


你可以使用维基百科库:

https://wikipedia.readthedocs.io/en/latest/

这是图书馆的一个例子

wikipedia.search(query, results=10, suggestion=False)¶

推荐阅读