我需要在下面的代码片段中提取结束标记和
标记之间的数据:
<td><b>First Type :</b>W<br><b>Second Type :</b>65<br><b>Third Type :</b>3</td>
我需要的是:W, 65, 3
但问题是这些值也可以为空,比如-
<td><b>First Type :</b><br><b>Second Type :</b><br><b>Third Type :</b></td>
如果存在其他空字符串,我想获取这些值
我尝试使用 nextSibling 和 find_next('br') 但它返回了
<br><b>Second Type :</b><br><b>Third Type :</b></br></br>
和
<br><b>Third Type :</b></br>
如果标签之间不存在值(W、65、3)
</b> and <br>
我所需要的是,如果这些标签之间没有任何内容,它应该返回一个空字符串。
最佳答案
我会使用 <b>
由 </b>
标记标签策略,查看他们的信息类型 next_sibling
包含。
我只想检查他们的 next_sibling.string
不是 None
,并相应地附加列表 :)
>>> html = """<td><b>First Type :</b><br><b>Second Type :</b>65<br><b>Third Type :</b>3</td>"""
>>> soup = BeautifulSoup(html, "html.parser")
>>> b = soup.find_all("b")
>>> data = []
>>> for tag in b:
if tag.next_sibling.string == None:
data.append(" ")
else:
data.append(tag.next_sibling.string)
>>> data
[' ', u'65', u'3'] # Having removed the first string
希望这对您有所帮助!
关于python - 如何使用 BeautifulSoup 在两个不同的标签之间获取值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554274/