我想从一个复杂的新闻网站上提取这篇文章。示例HTML代码:
<div class="article-section clearfix">
<p style="line-height:1em;">
<span class="spTextSmaller">Wenig Zeit? Am Textende gibt's eine Zusammenfassung. </span>
</p>
<p>
<hr noshade="1"/>
</p>
<p>Das Ende der Welt ...</p>
<p>Brzezinski ... </p>
<p>blubla</p>
<p>tututut</p>
<div class="asset-box spPhotoGallery spPhotoGalleryZitat article-quote-gallery">
<div class="asset-title">"Ich werde es niemals ausschließen"</div>
<div class="zitat-box">
<a href="" class="zitat-box-button"><img src="..." height="48" width="48" alt="Zitate starten" />
</a><a href="..." title="Zitate starten" class="zitat-box-content">... </a></div>
<p>Zitate starten: Klicken Sie auf den Pfeil</p>
</div>
<p>Blabla ..."</p>
<p>randomletters </p>
</div>我希望提取类的标记之间的所有文本“文章-节清除,因此在本例中。
['Das Ende der Welt ... ', 'Brzezinski ... ', 'blubla', 'tututut', 'Blabla ..."', 'randomletters ']它不应该包括"Zitate : Klicken“,它是div大类”资产盒spPhotoGallery .“中的p标签。
目前我正在使用
textlist=[]
for tag in articlesoup.find_all("p"):
if(tag.parent["class"]==['article-section', 'clearfix']):
textlist.append(tag.get_text() + "\n")
else: continue 这会导致
KeyError:‘类
对于没有div class=的其他网页“资产盒spPhotoGallery spPhotoGalleryZitat文章-报价库”,它工作得很好。像“文章-图像-描述”这样的类没有问题。在这里,我还没有找到其他与美汤相关的问题的答案。
从“文章部分”、“清除”类中获取所有文本
for tag in articlesoup.find_all("div", class_=['article-section, 'clearfix']): tag. get_text()结果太多不必要的东西,这就是为什么我必须坚持上面提到的解决方案可能。我应该使用一些尝试方法来避免错误吗?谢谢你提前提供帮助
发布于 2016-08-17 15:22:09
你想要的是使用recursive=False
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for p in soup.find("div",class_="article-section clearfix").find_all("p", recursive=False):
text = p.find(text=True, recursive=False).strip()
if text:
print(text)soup.find(" div ",class_=“项目-区段清除”).find_all(“p”,recursive=False)获取div的所有子级,然后text = p.find(text=True,recursive=False).strip()查找p标记下的任何文本,不包括标记的子标记。
你可以看到在你的样本上运行,我们得到了我们想要的:
In [8]: html = """<div class="article-section clearfix">
<p styfrom bs4 import BeautifulSoup
html = """<div class="article-section clearfix">
<p styfrom bs4 import BeautifulSoup
html = """<div class="article-section clearfix">
<p style="line-height:1em;">
<span class="spTextSmaller">Wenig Zeit? Am Textende gibt's eine Zusammenfassung. </span>
</p>
<p>
<hr noshade="1"/>
</p>
<p>Das Ende der Welt ...</p>
<p>Brzezinski ... </p>
<p>blubla</p>
<p>tututut</p>
<div class="asset-box spPhotoGallery spPhotoGalleryZitat article-quote-gallery">
<div class="asset-title">"Ich werde es niemals ausschließen"</div>
<div class="zitat-box">
<a href="" class="zitat-box-button"><img src="..." height="48" width="48" alt="Zitate starten" />
</a><a href="..." title="Zitate starten" class="zitat-box-content">... </a></div>
<p>Zitate starten: Klicken Sie auf den Pfeil</p>
</div>
<p>Blabla ..."</p>
<p>randomletters </p>
</div>"""然后:
In [9]: soup = BeautifulSoup(html, "html.parser")
In [10]: for p in soup.find("div", class_="article-section clearfix").find_all("p", recursive=False):
....: text = p.find(text=True, recursive=False).strip()
....: if text:
....: print(text)
....:
Das Ende der Welt ...
Brzezinski ...
blubla
tututut
Blabla ..."
randomletters代码错误的原因是递归地查找p标记,其中至少有一个p标记有一个没有类的父标记,如下所示:
In [13]: html = """<div><p>foo</p> <>"""
In [14]: soup = BeautifulSoup(html, "html.parser")
In [15]: print(soup.find("p").parent["class"])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-15-c4921fc9e631> in <module>()
----> 1 print(soup.find("p").parent["class"])
/usr/lib/python3/dist-packages/bs4/element.py in __getitem__(self, key)
956 """tag[key] returns the value of the 'key' attribute for the tag,
957 and throws an exception if it's not there."""
--> 958 return self.attrs[key]
959
960 def __iter__(self):
KeyError: 'class'
In [16]: html = """<div class="bar"><p>foo</p> <>"""
In [17]: soup = BeautifulSoup(html, "html.parser")
In [18]: print(soup.find("p").parent["class"])
['bar']https://stackoverflow.com/questions/38998072
复制相似问题