在一段文本之后解析一段文本(使用 python Beautiful Soup)
Parsing a piece of text after another piece of text (Using python Beautiful Soup)
我要解析的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-Lay-MRT":
soup2=BeautifulSoup(webpage2)
for cell in soup2.findAll('h3'):
if 'MRT Stations Nearby' == cell.text:
for cell2 in cell.findAllNext('strong')[0]:
print(cell2)
如何获取下一段文本(距离)?我认为只需将 ('strong')[0] 更改为 ('br /') 就可以了,但没有用。
抱歉,如果问题很愚蠢,我们将不胜感激。
谢谢
你试过了吗for cell2 in cell.findAllNext('br')[0]:
...我认为你不需要“/”,因为那只意味着标签是自动关闭的
据我了解,问题的输入是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()
我要解析的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-Lay-MRT":
soup2=BeautifulSoup(webpage2)
for cell in soup2.findAll('h3'):
if 'MRT Stations Nearby' == cell.text:
for cell2 in cell.findAllNext('strong')[0]:
print(cell2)
如何获取下一段文本(距离)?我认为只需将 ('strong')[0] 更改为 ('br /') 就可以了,但没有用。
抱歉,如果问题很愚蠢,我们将不胜感激。
谢谢
你试过了吗for cell2 in cell.findAllNext('br')[0]:
...我认为你不需要“/”,因为那只意味着标签是自动关闭的
据我了解,问题的输入是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()