使用 BeautifulSoup for Python 来解析网页(不幸的是,它主要写在表格中)。
这是我正在尝试使用的内容的摘录
<tr>
<td colspan="4">
<div class="shortmenucats">
<span style="color: ">
-- Fresh Baked Pastries --
</span>
</div>
</td>
</tr>
<tr>
<td width="80%" valign="top">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td>
<div class="shortmenurecipes">
<span style="color: #000000"> Chocolate Doughnut Holes </span>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td width="5%" valign="top"></td>
<td width="10%" valign="top" align="right" colspan="1">
<div class="shortmenuprices">
<span style="color: #000000"></span>
</div>
</td>
<td width="5%" valign="top" colspan="1">
</td>
</tr>
这些是表中的两行,其中有 10 行,它们像这样交替(td 中的 div,td 中的表,td 中的 div,td 中的表等)。
我正在使用 BeautifulSoup 在父表上调用 find_all 并且由于嵌套表中的嵌套标签,它返回每隔一行的重复项。
我开始做一个
table.find_all('td', recursive=False)
但这根本没有返回任何 s 。如果我在父表上调用
findChildren()
,我会得到一个包含一个结果的列表,但它包含结果中的所有子项。难道我做错了什么?我不知道如何解决这个问题。
如果您想要我正在解析的实际网站,请访问:
http://138.23.12.141/foodpro/shortmenu.asp?sName=University+of+California%2C+Riverside+Dining+Services&locationNum=02&locationName=Lothian+Residential+Restaurant&naFlag=1
编码相当困惑。我只是想解析它。
任何帮助将不胜感激。即使这只是删除重复项的一种方式。
谢谢你。
最佳答案
您可以通过 HTML 中的深度来识别目标表。
下面是一些代码,它将选择嵌套在深度 3 的那些表:
tables = soup.findAll("table")
depth3 = []
for t in tables:
if len(t.find_parents("table")) == 3:
depth3.append(t)
对于您的页面,这将导致选择 6 个表格 - 三个用于标题(“早餐”、“午餐”、“晚餐”)和三个用于菜单。它们交替 - 标题、菜单、标题、菜单等,因此您可以只处理位置 1、3 和 5 的表格。
你的解析现在应该容易多了。
关于python - BeautifulSoup 忽略表格内的嵌套表格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28058203/