我不知道如何对BeautifulSoup进行编码,因此它只为我提供了所选标签中的文本。我得到的更多,如其孩子的文字(人)!
例如:
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)
输出:
“我想要这个文字”我不希望这个文字我不想要这个
“好”不好也不好
期望的输出:
“我想要这个文字”
“好”
答案 0 :(得分:5)
一个选项是获取contents
list的第一个元素:
for i in x:
print(i.contents[0])
另一个 - 找到第一个文本节点:
for i in x:
print(i.find(text=True))
两者都会打印出来:
"I want this text"
"Good"
答案 1 :(得分:-1)
from bs4 import BeautifulSoup
from bs4 import NavigableString
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:
if isinstance(i.next_element, NavigableString):#if li's next child is a string
print(i.next_element)