我要解析的HTML如下:
> </td> </tr> <!--MRT--> <tr><td colspan="2" style="border-top: 1px
> Dashed #CCC"><h3>MRT Stations Nearby</h3></td></tr><tr><td
> colspan="2"><table width="602" align="center" cellpadding="0"
> cellspacing="0"><tr><td width="261"><a
> href="/property/propertynearmrt/Boon-Lay-MRT/?t=dl&mid=12" title="Boon
> Lay MRT"><strong>Boon Lay MRT</strong></a><br />Distance :0.07km </td>从这里开始,我想得到距离(在这里是0.07公里)。我还使用以下代码解析站点名称“Boon”:
soup2=BeautifulSoup(webpage2)
for cell in soup2.findAll('h3'):
if 'MRT Stations Nearby' == cell.text:
for cell2 in cell.findAllNext('strong')[0]:
print(cell2)我如何获得下一段文字(距离)?我认为只需将“强”改为(“br/”)就行了,但它不起作用。
对不起,如果这个问题相当愚蠢,任何帮助都将不胜感激。
谢谢
发布于 2015-06-30 15:04:12
据我所知,问题的输入是MRT Stations Nearby文本。输出应该是0.07km。
在这种情况下,我们的想法是定位MRT Stations Nearby文本,找到tr父文件。在那里,找到下一个tr兄弟,并查找包含Distance文本的元素:
row = soup.find(text="MRT Stations Nearby").find_parent("tr").find_next_sibling("tr")
distance = row.find(text=lambda x: x and x.startswith("Distance"))
print distance.split(":")[-1].strip()发布于 2015-06-30 15:00:56
你试过for cell2 in cell.findAllNext('br')[0]: ..。我不认为你需要'/‘,因为这仅仅意味着标签是自动关闭的
https://stackoverflow.com/questions/31141724
复制相似问题