查找文本但跳过其他元素

时间:2016-06-07 05:31:08

标签: python web-scraping beautifulsoup

我目前正试图从“td'元素,但其中有更多的元素。所以find()返回td标签内的整个文本。这是代码:

<td class="some class">
  Some text that i want<br>
  <a href="some/link">some more text</a>       
  <span class="some other class">some more text</span>
  <br>
</td>

那么我想要的只是在td标签之后的下一个。我正在使用BeautifulSoup。

有关如何在没有其他元素的情况下获取文本的任何建议吗?

3 个答案:

答案 0 :(得分:1)

只有第一个文字,您才能获得“td&#39; class,将其转换为列表并获取第一个索引:

t ='''
<td class="some class">
  Some text that i want<br>
  <a href="some/link">some more text</a>       
  <span class="some other class">some more text</span>
  <br>
</td>
'''

soup = BeautifulSoup(t, "html.parser")

text = list(soup.find('td'))[0]

答案 1 :(得分:0)

只需在该元素上使用.text即可。

b=bs4.BeautifulSoup("""<td class="some class">
Some text that i want<br>
<a href="some/link">some more text</a>
<span class="some other class">some more text</span>
<br>
</td>""")
txt = b.find('td').text
# txt will be: u'\n  Some text that i want\nsome more text\nsome more text\n\n'

答案 2 :(得分:0)

获取&#34;我想要的某些文字的更常见方式&#34;将使用find(text=True),它会在标记内找到第一个文本节点

from bs4 import BeautifulSoup

data = """<td class="some class">
  Some text that i want<br>
  <a href="some/link">some more text</a>
  <span class="some other class">some more text</span>
  <br>
</td>"""

soup = BeautifulSoup(data, "html.parser")
text = soup.find("td", class_="some class").find(text=True)
print(text.strip())  # prints "Some text that i want"

另一种选择是从.stripped_strings中获取文本节点,其中包含标记内的所有文本节点(另外修剪/剥离):

next(soup.find("td", class_="some class").stripped_strings)