我正在尝试解析网站并检索包含超链接的文本。 例如:
<a href="www.example.com">This is an Example</a>
我需要检索“这是一个示例”,我可以对没有损坏标签的页面执行此操作。在以下情况下我无法检索:
<html>
<body>
<a href = "http:\\www.google.com">Google<br>
<a href = "http:\\www.example.com">Example</a>
</body>
</html>
在这种情况下,代码无法检索 Google,因为链接 google 的标签已损坏,并且只给我“示例”。有没有办法也检索“Google”?
我的代码在这里:
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
f = open("sol.html","r")
soup = BeautifulSoup(f,parse_only=SoupStrainer('a'))
for link in soup.findAll('a',text=True):
print link.renderContents();
请注意 sol.html 包含上面给出的 html 代码本身。
谢谢 - AJ
最佳答案
从代码中删除 text=True
,它应该可以正常工作:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''
... <html>
... <body>
... <a href = "http:\\www.google.com">Google<br>
... <a href = "http:\\www.example.com">Example</a>
... </body>
... </html>
... ''')
>>> [a.get_text().strip() for a in soup.find_all('a')]
[u'Google', u'Example']
>>> [a.get_text().strip() for a in soup.find_all('a', text=True)]
[u'Example']
关于python - 使用 Beautiful Soup 从损坏的 <a> 标签中检索内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13945523/