【问题标题】:How to get the text of nested tag with Beautifulsoup in Python?如何在 Python 中使用 Beautifulsoup 获取嵌套标签的文本?
【发布时间】:2020-12-23 15:39:28
【问题描述】:

运行这段代码后

section = soup.find_all('section', class_='b-branches')

我明白了

<div class="b-branches__item"><i class="icon fa"><b>Firm</b> </i>RJT Roadlines</div>

现在我只想提取 RJIT Roadlines 而不是...公司

所以我尝试了

for i in section: firm = i.find('div', class_='b-branches__item') print(firm)

它将返回 FirmRJIT Roadlines

那么,如何只提取 div 标签的文本??

【问题讨论】:

  • 欢迎来到 Stack Overflow。在寻求调试帮助时,我们要求您通过创建minimal reproducible example 来压缩您的代码。这有助于人们无需阅读整个代码即可了解您的问题。

标签: python html web-scraping


【解决方案1】:

您可以使用tag.contents[1] 来获得预期的输出。

示例:

from bs4 import BeautifulSoup

html = """
<div class="b-branches__item"><i class="icon fa"><b>Firm</b> </i>RJT Roadlines</div>
"""

soup=BeautifulSoup(html,'html.parser')

tag = soup.find('div', class_='b-branches__item')
print(tag.contents[1])

输出:

RJT Roadlines

【讨论】:

  • 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受 - stackoverflow.com/help/someone-answers
  • 假设在使用 print(tag.contents[1]) 后我得到了输出,即 987,9887。现在如何将它们存储在两个不同的变量 x1、x2 中。
  • 不清楚你的意思,你应该用完整的例子将它作为新问题提出。如果我理解正确,只需分配它x1 = soup.find('div', class_='b-branches__item').contents[1]
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2021-05-15
相关资源
最近更新 更多