首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“美丽汤”中特定类的文本解析错误

“美丽汤”中特定类的文本解析错误
EN

Stack Overflow用户
提问于 2016-08-17 13:29:13
回答 1查看 454关注 0票数 1

我想从一个复杂的新闻网站上提取这篇文章。示例HTML代码:

代码语言:javascript
复制
<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>

我希望提取类的标记之间的所有文本“文章-节清除,因此在本例中。

代码语言:javascript
复制
['Das Ende der Welt ... ', 'Brzezinski ... ', 'blubla', 'tututut', 'Blabla ..."', 'randomletters ']

它不应该包括"Zitate : Klicken“,它是div大类”资产盒spPhotoGallery .“中的p标签。

目前我正在使用

代码语言:javascript
复制
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文章-报价库”,它工作得很好。像“文章-图像-描述”这样的类没有问题。在这里,我还没有找到其他与美汤相关的问题的答案。

从“文章部分”、“清除”类中获取所有文本

代码语言:javascript
复制
for tag in articlesoup.find_all("div", class_=['article-section, 'clearfix']): tag. get_text()

结果太多不必要的东西,这就是为什么我必须坚持上面提到的解决方案可能。我应该使用一些尝试方法来避免错误吗?谢谢你提前提供帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-17 15:22:09

你想要的是使用recursive=False

代码语言:javascript
复制
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标记下的任何文本,不包括标记的子标记。

你可以看到在你的样本上运行,我们得到了我们想要的:

代码语言:javascript
复制
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>"""

然后:

代码语言:javascript
复制
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标记有一个没有类的父标记,如下所示:

代码语言:javascript
复制
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']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38998072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档