【问题标题】:Python Beautiful Soup print specific lines within multiline <p> containing stringPython Beautiful Soup 在包含字符串的多行 <p> 中打印特定行
【发布时间】:2019-04-16 04:58:55
【问题描述】:

如何在一个包含特定字符串的&lt;p&gt; 标记中仅获取/打印大的多行文本的行?在网站上,这些行是用&lt;br&gt; 标签实现的。没有关闭 &lt;/p&gt; 标记。

网站的基本结构:

<p style="line-height: 150%">
I need a big cup of coffee and cookies.
<br>
I do not like tea with milk.
<br>
I can't live without coffee and cookies.
<br>
...

假设我只想获取/打印包含“咖啡和饼干”字样的行。因此,在这种情况下,应该只打印此&lt;p&gt; 的第一和第三“行”/ 句子。

我在 Python 3.7.1 下安装了 Beautiful Soup 4.6.3。

findAll 似乎是面向标签的并返回整​​个&lt;p&gt;,对吗?那我怎么能意识到呢?也许使用正则表达式或其他模式?

【问题讨论】:

    标签: python html web-scraping beautifulsoup screen-scraping


    【解决方案1】:

    如果我能正确理解您的要求,那么以下 sn-p 应该可以帮助您:

    from bs4 import BeautifulSoup
    
    htmlelem = """
        <p style="line-height: 150%">
        I need a big cup of coffee and cookies.
        <br>
        I do not like tea with milk.
        <br>
        I can't live without coffee and cookies.
        <br>
    """
    
    soup = BeautifulSoup(htmlelem, 'html.parser')
    for paragraph in soup.find_all('p'):
        if not "coffee and cookies" in paragraph.text:continue
        print(paragraph.get_text(strip=True))
    

    【讨论】:

    【解决方案2】:

    你能在 \n 上拆分吗?

    from bs4 import BeautifulSoup
    
    html = """
        <p style="line-height: 150%">
        I need a big cup of coffee and cookies.
        <br>
        I do not like tea with milk.
        <br>
        I can't live without coffee and cookies.
        <br>
    """
    
    soup = BeautifulSoup(html, 'html.parser')
    for item in soup.select('p'):
        r1 = item.text.split('\n')
        for nextItem in r1:
            if "coffee and cookies" in nextItem:
                print(nextItem)
    

    【讨论】:

    • 谢谢,这个例子也可以。如果我们在同一行中也有一个 -tag 并且也应该打印出来怎么办?
    • 喜欢 soup.select('p,a') 吗?这将收集 p 和 a 标签元素。
    • 这只会打印来自 a 的文本,对吧?如果我还需要 href 值怎么办?
    • 它会抓取这些元素,然后你会从 a 标签中检索 href 值,尽管最好使用 soup.select('p, a[href]') stackoverflow.com/questions/1080411/…
    【解决方案3】:

    使用str()bs4.element 转换为字符串,然后您可以将其与“咖啡和饼干”进行比较

    from bs4 import BeautifulSoup
    
    html_doc = """<p style="line-height: 150%">
        I need a big cup of coffee and cookies. <a href="aaa">aa</a>
        <br>
        I do not like tea with milk.
        <br>
        I can't live without coffee and cookies.
        <br>"""
    
    soup = BeautifulSoup(html_doc, 'html.parser')
    paragraph = soup.find('p')
    
    for p in paragraph:
      if 'coffee and cookies' in str(p):
        next_is_a = p.find_next_sibling('a')
        if next_is_a:
          print(p.strip() + ' ' + str(next_is_a))
        else:
          print(p.strip())
    

    【讨论】:

    猜你喜欢
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    相关资源
    最近更新 更多