【问题标题】:How to get text from <p class=" "> tag using BeautifulSoup4如何使用 BeautifulSoup4 从 <p class=" "> 标签获取文本
【发布时间】:2021-02-14 07:38:52
【问题描述】:

我正在抓取一些网页并尝试从所有网页中获取简单的文本

<p> </p>

标签。在一个特定的例子中,我遇到了一个带有类的“p”标签:

<p class="SimpleBlock-module_p__Q3azD "> Some text here. </p>

现在使用一个简单的:

Text = soup.findAll("p")

结果:

Text = SimpleBlock-module_p__Q3azD  Some text here.

如何只获取上面Text中不包括类名的文本部分。

我想要一个适用于所有情况的通用解决方案,无论“p”标签中是否存在类。

我在 Windows 10 上使用 Python3、请求和 BeautifulSoup4。

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    试试这个:

    from bs4 import BeautifulSoup
    
    p = """<p class="SimpleBlock-module_p__Q3azD "> Some text here. </p>"""
    print(BeautifulSoup(p, "html.parser").find("p").getText(strip=True))
    

    输出:

    Some text here.
    

    【讨论】:

      【解决方案2】:

      在 BeautifulSoup 4 中,findAll 不再存在 (bs3) 并被 find_all 取代

      find_all 提供了一个列表,因此在您的示例中,您应该使用:

      Text[0].string
      

      【讨论】:

        猜你喜欢
        • 2017-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        相关资源
        最近更新 更多