【问题标题】:Extract subclass from class using beautifulsoup使用 beautifulsoup 从类中提取子类
【发布时间】:2018-05-28 06:43:22
【问题描述】:

我正在使用 Python 3.6.3 处理 Goodreads 上的页面中的以下 HTML sn-p:

<div class="quoteText">
      “Don't cry because it's over, smile because it happened.”
  <br/>  ―
    <a class="authorOrTitle" href="/author/show/61105.Dr_Seuss">Dr. Seuss</a>
</div>, <div class="quoteText">

我使用 BeautifulSoup 来抓取 HTML 并仅隔离上面 sn-p 中看到的“quoteText”类。现在,我想将引用和作者姓名保存为单独的字符串。我能够使用

获得作者姓名
(quote_tag.find(class_="quoteText")).text

我不确定如何为报价做同样的事情。我猜我需要一种方法从输出中删除子类并尝试使用 extract 方法。

quote.extract(class_="authorOrTitle")

但我收到一条错误消息,提示 extract got an unexpected keyword argument 'class_' 还有其他方法可以做我想做的事情吗?

这是我第一次在这里发帖,如果帖子不符合特定的特定性/格式/其他标准,我深表歉意。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    PageElement.extract() 从树中删除标签或字符串。它 返回提取的标签或字符串

    from bs4 import BeautifulSoup
    a='''<div class="quoteText">
          “Don't cry because it's over, smile because it happened.”
      <br/>  -
        <a class="authorOrTitle" href="/author/show/61105.Dr_Seuss">Dr. Seuss</a>
    </div>, <div class="quoteText">'''
    s=BeautifulSoup(a,'lxml')
    s.find(class_="authorOrTitle").extract()
    print(s.text)
    

    【讨论】:

      猜你喜欢
      • 2016-04-19
      • 1970-01-01
      • 2018-06-06
      • 2023-03-18
      • 2020-12-23
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多