【发布时间】:2020-12-15 18:44:42
【问题描述】:
我正在做一个图表项目,我想要一种有效的方法来从特定的英文维基百科文章中获取指向其他英文维基百科文章的所有链接。
目前我在使用bs4和Python,但对bs4了解不多。
这是我现在拥有的:
##### Imports #####
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
##### Functions #####
parser = 'html.parser'
resp = requests.get("https://en.wikipedia.org/wiki/Influenza")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type','').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, parser, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
问题在于我收到了许多不需要的链接(非英文链接或非文章链接)。我认为我对 HTML 的了解不足以解决这个问题,而且我不想简单地过滤从上述 find_all() 调用中给我的每个链接,因为那样效率低下。
任何建议将不胜感激。 提前致谢!
【问题讨论】:
-
stackoverflow.com/questions/1080411/… 应该对这个问题有所了解
-
如果你仔细观察,你会发现维基百科文章上的所有链接都以
href开头/wiki/...。 -
非英语链接通常位于页面左侧 - 带有翻译链接,它们的
href不以/wiki/开头,所以没问题 -
@AlexLarionov 这似乎很有用,但我不确定从这里去哪里。我尝试做 soup.findall(href=re.compile("/wiki/")) 但我仍然得到非英语页面
-
@CalebBynum 打开一些 Wiki 页面并找到不需要的非英语链接。单击 RMB 并打开类似“Inspect element”之类的内容,您将在其中看到
a元素在实际 HTML 中的样子。您可能会发现一些class/id/href属性可以区分英语和非英语