【问题标题】:BS4 Grabbing Text in Between <p> Tags that Follow PatternBS4 在遵循模式的 <p> 标签之间抓取文本
【发布时间】:2021-04-14 14:11:54
【问题描述】:

我正在尝试使用遵循此模式的 BS4 在 python 中使用网站:

<p>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
</p>

我为此编写的代码跳过了“Text 1”和“Text 4”:

            for br in scraper.findAll('br'):
                next_s = br.nextSibling
                if not (next_s and isinstance(next_s,NavigableString)):
                    continue
                next2_s = next_s.nextSibling
                if next2_s and isinstance(next2_s,Tag) and next2_s.name == 'br':
                    text = str(next_s).strip()
                    if text:
                        wanted_text = next_s.split('Text ')[1]

我知道它没有抓取 p 标签中的第一个和最后一个文本的原因是因为我的第二个 if 语句,因此我试图弄清楚是否有不同的方法来解析它。

一旦我能够获取每个“Text 1”字符串,我将使用正则表达式解析每个字符串以获取我实际需要的内容,因此此代码的所需输出将是 next_s = "Text 1"

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    对于这类任务,您可以使用 .get_text()separator= 参数,然后在此分隔符上拆分:

    from bs4 import BeautifulSoup
        
    html_doc = """
    <p>
    Text 1
    <br/>
    Text 2
    <br/>
    Text 3
    <br/>
    Text 4
    </p>
    """
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    texts = soup.find("p").get_text(strip=True, separator="|").split("|")  # use separator not included in the text
    print(texts)
    

    打印:

    ['Text 1', 'Text 2', 'Text 3', 'Text 4']
    

    只获取第一个文本:

    print(texts[0])
    

    打印:

    Text 1
    

    或者:使用.find_all()text=True

    texts = [t.strip() for t in soup.find("p").find_all(text=True, recursive=False)]
    print(texts)
    

    【讨论】:

    • @SD_23 你也可以用.find_all(text=True, recursive=False),我把它加到我的答案里了。
    • 这是做同样事情的另一种方式texts = [i.strip() for i in soup.find("p").strings]
    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2021-09-07
    • 2018-04-24
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多