使用 BeautifulSoup,如何仅从特定选择器中获取文本而没有孩子中的文本? [英] Using BeautifulSoup, how to get text only from the specific selector without the text in the children?
本文介绍了使用 BeautifulSoup,如何仅从特定选择器中获取文本而没有孩子中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何编码 BeautifulSoup
以便它只给我来自所选标签的文本.我得到了更多诸如它的孩子(们)的文字!
I don't know how to code BeautifulSoup
so that it gives me only the text from the selected tag. I get more such as the text of its child(ren)!
例如:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="left"><ul><li>"I want this text"<a href="someurl.com"> I don\'t want this text</a><p>I don\'t want this either</li><li>"Good"<a href="someurl.com"> Not Good</a><p> Not Good either</li></ul></div>', "html5lib")
x = soup.select('ul > li')
for i in x:
print(i.text)
输出:
我想要这个文本"我不要这个文字我也不要这个
"I want this text" I don't want this textI don't want this either
好"不好也不好
期望的输出:
我想要这个文本"
好"
推荐答案
一个选择是获取 contents
列表:
One option would be to get the first element of the contents
list:
for i in x:
print(i.contents[0])
另一个 - 找到第一个文本节点:
Another - find the first text node:
for i in x:
print(i.find(text=True))
两者都会打印:
"I want this text"
"Good"
这篇关于使用 BeautifulSoup,如何仅从特定选择器中获取文本而没有孩子中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文