【发布时间】:2020-04-05 00:04:00
【问题描述】:
我正在尝试解析一组表格,其中列出了有关智能手机的信息。例如this link。我只是想获得 4 个我需要的特定字段,而获得第四个字段让我发疯。
似乎 HTML 格式错误。我们有几个表按顺序放置到 html 中。前5个还可以,但是第六个表以</td></tr></table>结尾,关闭了一个<td>和一个<tr>,它们以前没有打开过(或者至少我认为这是问题所在):
<table cellspacing="0">
<tr>
<th rowspan="5" scope="row">Memory</th>
<td class="ttl"><a href="glossary.php3?term=memory-card-slot">Card slot</a></td>
<td class="nfo" data-spec="memoryslot">microSD, up to 256 GB (uses shared SIM slot)</td></tr>
<tr>
<td class="ttl"><a href="glossary.php3?term=dynamic-memory">Internal</a></td>
<td class="nfo" data-spec="internalmemory">64GB 6GB RAM, 128GB 6GB RAM, 128GB 8GB RAM, 256GB 8GB RAM</td>
</tr>
<tr><td class="ttl"> </td><td class="nfo" data-spec="memoryother">UFS2.1</td></tr>
</td>
</tr>
</table>
另外,第七张表的列表很糟糕,但我想这对bs4来说应该不是问题。
因此,如果我尝试使用 CSS 选择器从表 7 到最后一个表中获取任何值,选择器将返回 None。事实上,如果我只是使用一个选择器来获取所有的表,它只是选择了前 6 个表:
dsoup = BeautifulSoup(dr.content, 'html.parser')
dsel = dsoup.select('#specs-list > table')
print('Found {} tables'.format(len(dsel))) # Prints 6 tables
dsel = dsoup.select_one('#specs-list > table:nth-of-type(10) > tbody > tr:nth-of-type(3) > td.nfo')
print(dsel.text.split('\n')) # None
所以问题是,有没有办法解析像这样的格式错误的 HTML 的情况,还是不可能?
【问题讨论】:
标签: python html beautifulsoup css-selectors