【问题标题】:How to extract text inside a <p> with a <small> tag如何使用 <small> 标签提取 <p> 内的文本
【发布时间】:2019-12-14 12:24:50
【问题描述】:

目前我正在抓取一个新闻网站进行研究工作,我使用 python+BeautifulSoup 如下

newsPageSoup = BeautifulSoup(newsPage.content, 'html.parser', from_encoding="iso 639-3")
newsText = newsPageSoup.find(class_='post-content').get_text()

从以下html代码中获取文本部分。效果很好。

<p class="post-content">The completion of the sixth review, upon the granting of a waiver of non‑observance for the end‑June 2019, performance criterion on the primary balance</p>

但情况是我想从以下中提取文本部分 Andrew

<p class="text-primary" style="color : #2793ed; font:Arial, Helvetica, sans-serif; font-size:14px; font-weight:normal">Andrew <small style="color:#999999; font-size:11px">Friday, 13 December 2019 07:58 PM </small> </p>

所以我使用了和上面一样的python代码

readerNames = newsPageSoup.find(class_='text-primary').get_text()

但它给出了以下错误

AttributeError: 'NoneType' object has no attribute 'get_text'

我认为这是因为&lt;p&gt; 标签内的&lt;small&gt; 标签。所以他们有办法做到这一点吗?请帮忙

【问题讨论】:

    标签: python html css beautifulsoup


    【解决方案1】:

    您可以这样访问文本值:

    import bs4
    l = '<p class="text-primary" style="color : #2793ed; font:Arial, Helvetica, sans-serif; font-size:14px; font-weight:normal">Andrew <small style="color:#999999;font-size:11px">Friday, 13 December 2019 07:58 PM </small> </p>'
    newsPageSoup = bs4.BeautifulSoup(l)
    readerNames = newsPageSoup.find(class_='text-primary').text
    

    【讨论】:

    • @BenSV 将其标记为正确答案,如果您认为它是正确答案,请投票 :)
    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多