python - 使用 Beautiful Soup 从损坏的 <a> 标签中检索内容

标签 python web-scraping beautifulsoup

我正在尝试解析网站并检索包含超链接的文本。 例如:

<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/

相关文章:

json - 将 colly 包输出文本添加到 golang 中的映射

javascript - 是否可以用漂亮的汤从动态图中提取数据?

python - 将继承字段添加到 TreeView product_uom_categ - Odoo v9

python - 属性错误 : 'module' object has no attribute 'Zeros'

python - 如何在 Scrapy 中暂停爬虫

Python 分页循环

Python Beautifulsoup get_text() 没有获取所有文本

python - 楼层划分和划分的运算符优先级

python - nltk.tokenize 从 Shell 正确执行,但作为脚本文件出现错误

python - 使用 beautifulsoup 抓取数据结果为 404