Python 在HTML、BeautifulSoup中匹配特定表
我有这个问题。页面上有几张类似的表格,我正在努力清理Python 在HTML、BeautifulSoup中匹配特定表,python,python-2.7,beautifulsoup,Python,Python 2.7,Beautifulsoup,我有这个问题。页面上有几张类似的表格,我正在努力清理 <h2 class="tabellen_ueberschrift al">Points</h2> <div class="fl" style="width:49%;"> <table class="tabelle_grafik lh" cellpadding="2" cellspacing="1"> 需要一些帮助。这对我很有用。找到前面的兄弟姐妹,如果您找到一个h2,它的文本点位于具
<h2 class="tabellen_ueberschrift al">Points</h2>
<div class="fl" style="width:49%;">
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">
需要一些帮助。这对我很有用。找到前面的兄弟姐妹,如果您找到一个h2,它的文本点位于具有不同文本内容的h2标记之前,那么您就找到了一个好的表
from BeautifulSoup import BeautifulSoup
t="""
<h2 class="tabellen_ueberschrift al">Points</h2>
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">
<th><td>yes me!</th></td></table>
<h2 class="tabellen_ueberschrift al">Bad</h2>
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">
<th><td>woo woo</td></th></table>
"""
soup = BeautifulSoup(t)
for ta in soup.findAll('table'):
for s in ta.findPreviousSiblings():
if s.name == u'h2':
if s.text == u'Points':
print ta
else:
break;
这对我有用。找到前面的兄弟姐妹,如果您找到一个h2,它的文本点位于具有不同文本内容的h2标记之前,那么您就找到了一个好的表
from BeautifulSoup import BeautifulSoup
t="""
<h2 class="tabellen_ueberschrift al">Points</h2>
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">
<th><td>yes me!</th></td></table>
<h2 class="tabellen_ueberschrift al">Bad</h2>
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">
<th><td>woo woo</td></th></table>
"""
soup = BeautifulSoup(t)
for ta in soup.findAll('table'):
for s in ta.findPreviousSiblings():
if s.name == u'h2':
if s.text == u'Points':
print ta
else:
break;
看来这是我的工作。但是,BeautifulSoup不支持XPath表达式 考虑切换到或 仅供参考,对于测试xml,如:
<html>
<h2 class="tabellen_ueberschrift al">Points</h2>
<div class="fl" style="width:49%;">
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">a</table>
</div>
<h2 class="tabellen_ueberschrift al">Illegal</h2>
<div class="fl" style="width:49%;">
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">b</table>
</div>
</html>
看来这是我的工作。但是,BeautifulSoup不支持XPath表达式 考虑切换到或 仅供参考,对于测试xml,如:
<html>
<h2 class="tabellen_ueberschrift al">Points</h2>
<div class="fl" style="width:49%;">
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">a</table>
</div>
<h2 class="tabellen_ueberschrift al">Illegal</h2>
<div class="fl" style="width:49%;">
<table class="tabelle_grafik lh" cellpadding="2" cellspacing="1">b</table>
</div>
</html>
这可以通过BeautifulSoup实现。您可以通过同级遍历表,找到您要查找的表。看沃斯普林的回答。@serk,是的,谢谢。我只是想指出xpath是一个适合这项工作的工具。因此,我认为答案可以留在这里,作为问题的替代解决方案。这可以通过BeautifulSoup实现。您可以通过同级遍历表,找到您要查找的表。看沃斯普林的回答。@serk,是的,谢谢。我只是想指出xpath是一个适合这项工作的工具。因此,我认为答案可以留在这里,作为解决问题的替代方案。