在 p-tag 中查找文本,其中包含 beautifulsoup 的 span-tag
Finding text in p-tag which includes a span-tag with beautifulsoup
使用 beautifulsoup 我需要在 <p>
标签内找到文本,其中有一个 <span>
标签,但我只对来自的文本感兴趣<p>
-标签。仅仅找到 <p>
-tags 就会给出太多结果,所以我想通过跨度来限制它们。
这是我想要实现的示例:
text_example = '<p>Hello <span>World</span></p>'
soup = BeautifulSoup(text_example, 'html.parser')
print(soup.find('p').string) # Prints None
print(soup.find('p').find('span').string) # Prints World
如何获取值:'Hello'?
您可以在 find
:
中使用 text
和 recursive
参数
out = soup.find('p').find(text=True, recursive=False).rstrip()
输出:
'Hello'
使用 beautifulsoup 我需要在 <p>
标签内找到文本,其中有一个 <span>
标签,但我只对来自的文本感兴趣<p>
-标签。仅仅找到 <p>
-tags 就会给出太多结果,所以我想通过跨度来限制它们。
这是我想要实现的示例:
text_example = '<p>Hello <span>World</span></p>'
soup = BeautifulSoup(text_example, 'html.parser')
print(soup.find('p').string) # Prints None
print(soup.find('p').find('span').string) # Prints World
如何获取值:'Hello'?
您可以在 find
:
text
和 recursive
参数
out = soup.find('p').find(text=True, recursive=False).rstrip()
输出:
'Hello'