2016-06-07 52 views
0

我目前试图从“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。

任何建议如何让文本没有其他元素?

回答

1

对于第一个文本只有你可以得到“TD”级,将其转换成一个列表,并获得第一指数:

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] 
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' 
+0

.text返回所有文本元素。所以结果将是“一些文本,我想要更多的文字一些更多的文字” – Merithor

+0

然后简单地将其转换为一个列表,并使用第一个元素,如在其他答案中的b.find('TD')。 –

0

更常见的方式得到“一些文字,我想”是使用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)