【问题标题】:beautifulsoup get only string directly inside tagbeautifulsoup 只在标签内直接获取字符串
【发布时间】:2021-03-14 18:31:23
【问题描述】:

我有一个这种格式的 BeautifulSoup

<div class='text'>
<h3> text </h3>
<p> some more text </p>
"text here <b> is </b> important"
</div>

如何仅提取字符串“此处的文本很重要”,省略 h3 和 p 元素,但粗体标记文本保留在输出中

非常感谢

【问题讨论】:

  • 是用正则表达式可接受的解决方案解析这个字符串吗? (re.findall(r'"[^"]+.',your_string))

标签: python web-scraping beautifulsoup


【解决方案1】:

对于这种特定格式,请尝试将 .next_siblings 用于元素 p

import bs4
from bs4 import BeautifulSoup

text = '''<div class='text'>
<h3> text </h3>
<p> some more text </p>
"text here <b> is </b> important"</div>'''

response = BeautifulSoup(text)

str_list = []
for x in (response.p.next_siblings):
    # filter of "b" tag and get its text
    if type(x) == bs4.element.Tag:
        str_list.append(x.get_text().strip())
    else :
        str_list.append(x.strip())

output = " ".join(str_list)
print(output)

这给了我输出:

“这里的文字很重要”

【讨论】:

    【解决方案2】:

    您可以使用tag.decompose() 删除不需要的标签,然后提取剩余的文本。

    from bs4 import BeautifulSoup
    spam = """<div class='text'>
    <h3> text </h3>
    <p> some more text </p>
    "text here <b> is </b> important"
    </div>"""
    
    soup = BeautifulSoup(spam, 'html.parser')
    div = soup.find('div')
    for tag in ('h3', 'p'):
        div.find(tag).decompose()
    print(div.text.strip())
    

    输出

    "text here  is  important"
    

    【讨论】:

      【解决方案3】:
      html = "<div class='text'>
      <h3> text </h3>
      <p> some more text </p>
      "text here <b> is </b> important"
      </div>"
      
      soup = BeautifulSoup(html,'lxml')
      
      for b_element in soup.find_all('b'):
         b_element.unwrap() #removes the <b> </b> while keeping the text intact
      
      soup.smooth() #fixes any consecutive unwrapped text into continuous text
      
      #finally getting only parent text now using below code
      elements = soup.find_all('div')
      
      for element in elements:
         fulltextofelement = element.find(text=True, recursive=True)
         onlyparenttext = element.find(text=True, recursive=False)
      
      

      【讨论】:

        猜你喜欢
        • 2019-08-12
        • 1970-01-01
        • 2015-03-08
        • 1970-01-01
        • 1970-01-01
        • 2015-06-27
        • 2017-02-02
        • 1970-01-01
        相关资源
        最近更新 更多