【问题标题】:How to retrieve text data from multiple HTML tags?如何从多个 HTML 标签中检索文本数据?
【发布时间】:2021-02-25 02:37:23
【问题描述】:

我将以下 HTML sn-p 输出存储在名为 content 类型为 bs4.element.Tag 的变量中。

<li class="item">
                                            Alpha-tocopherol
                                            <em>see</em>
<a href="https://medlineplus.gov/vitamine.html">Vitamin E</a>
</li>

str(content) 输出:

'<li class="item">\n                                            Alpha-tocopherol\n                                            <em>see</em>\n<a href="https://medlineplus.gov/vitamine.html">Vitamin E</a>\n</li>'

我想使用 Python 作为输出:['Alpha-tocopherol', 'Vitamin E']。 我尝试了以下方法,但它是错误的:

regex = re.compile('(\w+\s+)\n')
regex.sub('', content.text).split()

【问题讨论】:

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


【解决方案1】:

您可以通过.contents方法获取第一个标签,然后使用.find_next()方法搜索a标签。

from bs4 import BeautifulSoup

html = """
<li class="item">
Alpha-tocopherol
<em>see</em>
<a href="https://medlineplus.gov/vitamine.html">Vitamin E</a>
</li>
"""
soup = BeautifulSoup(html, "html.parser")

for tag in soup.find_all("li", class_="item"):
    print([tag.contents[0].strip(), tag.find_next("a").text])

输出:

['Alpha-tocopherol', 'Vitamin E']

【讨论】:

    【解决方案2】:

    这两种方法都会生成您想要的列表。但是,对于第一个,这取决于 html 元素的解析方式。如果有分页符\n,你将不得不做一些额外的解析。

    html = '''<li class="item">Alpha-tocopherol<em>see</em><a href="https://medlineplus.gov/vitamine.html">Vitamin E</a></li>'''
    soup = BeautifulSoup(html, "html.parser")
    
    soup.text.split('see') # option 1, get all text and parse accordingly from soup object
    
    soup.find('li', class_='item').text.split('see') # option 2, get text from li element (seems like it'd be less efficient to do this)
    

    输出

    ['Alpha-tocopherol, 'Vitamin E']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      相关资源
      最近更新 更多