【发布时间】:2018-04-20 01:05:03
【问题描述】:
我在 python 中编写了一个脚本来从一些 html 元素中抓取一些文本。当我执行我的脚本时,它会为我提供其中所有可用的文本。我不希望在p 标记中获取文本。几天前,当我浏览BeautifulSoup 文档时,我发现了一个方法.decompose()。虽然我不明白那是做什么的,但我想我可以试一试。但是,在执行时,我得到一个错误。
这是脚本:
html_elem ='''
<div class="track">
<p id="core">
pop singer<span class="lnkcat"> intranet </span>
</p>
<p id="crude">
songs<span class="lnkitm"> online </span>
</p>
<p id="evergreen">
instrumental<span class="lnkapt"> hotline </span>
</p>
<a href="http://link" target="_blank">track one</a>
<a href="http://link" target="_blank">track two</a>
<a href="http://link" target="_blank">track three</a>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_elem, "lxml")
item = soup.find_all(class_="track")
# item.p.decompose()
for elem in item:
print(elem.text.strip())
当我取消注释包含 .decompose() 的行并运行时出现此错误:
Traceback (most recent call last):
File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\Social.py", line 28, in <module>
item.p.decompose()
AttributeError: 'ResultSet' object has no attribute 'p'
顺便说一句,仅使用.find_all("a"),我可以获得所需的数据,但即使我选择track 类,我也希望知道/学习我只会得到a 标记中的文本,不包括@ 中的文本987654331@标签。
【问题讨论】:
-
我认为错误是因为 find_all() 返回一个列表。 item[0].p.decompose() 应该可以解决这个问题。
-
你快到了@Swakeert Jain。现在它丢弃了第一个
p标记。剩下的两个p标签呢?非常感谢您的收获。 -
for p in item[0]("p"): p.decompose() 这应该这样做。 stackoverflow.com/a/39904439/5561737
标签: python python-3.x web-scraping beautifulsoup