BeautifulSoup - 获取两个标签之间的字符串

问题描述:

我想使用BeautifulSoup来捕获两个HTML标签之间的所有内容。BeautifulSoup - 获取两个标签之间的字符串

这是HTML代码的片段,我关心的是:

<br>NEFS VII &amp; VIII Manager<br>

所以,即使我的HTML的了解不多,我可以看到,我需要捕获<br>标签和获取内容它们之间。我的问题似乎与此类似(Python HTML Parsing Between two tags),其中解决方案是使用soup.find('br').next_sibling,但尝试自己我遇到错误:

AttributeError: 'ResultSet' object has no attribute 'next_sibling'

这里是我的相关代码:

with open(file_path) as in_f: 
    msg = email.message_from_file(in_f) 

html_msg = msg.get_payload(1) 

body = html_msg.get_payload(decode=True)  

html = body.decode() 



br_tags = BeautifulSoup(html).find_all('br') 
print("br_tags:", br_tags) 
new_tags = BeautifulSoup(html).find_all('br').next_sibling 
print("new_tags:", new_tags) 
content = br_tags.string 
print("content:", content) 

命令print("br_tags:", br_tags)简单地打印出7 <br/>的,所有在列表中。尝试使用.next_sibling命令以及.string命令都会导致上面的属性错误。

我可能误解了BeautifulSoup是如何使用的,因为我是一个新手,但我会很感谢解决此问题的任何帮助,谢谢。

编辑:

大段HTML:

$0.30</span><o:p></o:p></p></td><td style='padding:0in 0in 0in 0in;height:15.0pt'></td><td style='padding:0in 0in 0in 0in;height:15.0pt'><p class=MsoNormal align=right style='text-align:right'><span style='font-size:10.0pt'>$492.30</span><o:p></o:p></p></td></tr><tr style='height:15.0pt'><td style='padding:0in 0in 0in 0in;height:15.0pt'><p class=MsoNormal><span style='font-size:10.0pt'>GB WINTER FLOUNDER</span><o:p></o:p></p></td><td style='padding:0in 0in 0in 0in;height:15.0pt'></td><td style='padding:0in 0in 0in 0in;height:15.0pt'></td><td style='padding:0in 0in 0in 0in;height:15.0pt'><p class=MsoNormal align=right style='text-align:right'><span style='font-size:10.0pt'>95,659</span><o:p></o:p></p></td><td style='padding:0in 0in 0in 0in;height:15.0pt'></td><td style='padding:0in 0in 0in 0in;height:15.0pt'><p class=MsoNormal align=right style='text-align:right'><span style='font-size:10.0pt'>$0.25</span><o:p></o:p></p></td><td style='padding:0in 0in 0in 0in;height:15.0pt'></td><td style='padding:0in 0in 0in 0in;height:15.0pt'><p class=MsoNormal align=right style='text-align:right'><span style='font-size:10.0pt'>$23,914.75</span><o:p></o:p></p></td></tr></table><p style='margin-bottom:12.0pt'><span style='font-family:"Arial","sans-serif";color:black'><o:p>&nbsp;</o:p></span></p><div><p class=MsoNormal><span style='font-family:"Arial","sans-serif";color:black'>Linda McCann<br>NEFS VII &amp; VIII Manager<br> 
+0

坏榜样 - 只有2'br's –

错误本身告诉你'ResultSet' object has no attribute 'next_sibling'ResultSet是当使用find_all()时得到的类型。

而且AttributeError出现,因为你也是你的脚本find_all()而不是find()使用:

new_tags = BeautifulSoup(html).find_all('br').next_sibling # yours 
new_tags = BeautifulSoup(html).find('br').next_sibling # correct 

要获得所有br标签文字使用,例如,这样的:大块

br_list = [] 
for i in soup.find_all('br'): 
    br_list.append(i.next_sibling) 
+0

好,这样的工作。但它只打印一个标签对:'new_tags:已发送:'。有没有办法让所有的对?如果可能的话,我最好把它们放到一个列表中,这样我就可以通过列表查找某些单词(例如'NEFS VII')。 – theprowler

+1

给人以多个标签更大的标记示例中它 –

+0

好吧,我会编辑HTML的较大块到我更新我的回答对你的要求的问题 – theprowler