1

我有一个这样的文件:

<table>
<span clas="city"> Miami </span> <span><a href="miami" > Miami </a> </span>
<span clas="city"> Orlando </span> <span><a href="orlando" > orlando </a></span>
</table>
<table>
<span clas="city"> Los Angeles </span> <span><a href="Los Angeles" > </a> </span>
<span clas="city"> San Diego </span>  <span><a href="Los Angeles" > San Diego</a> </span>
</table>

当表结束(没有while循环)时,如何将此正则表达式扩展re.compile('city">([^<]+)</span>')到属于同一州(表)的城市组,例如

State 1: Miami, Orlando
State 2: Los Angeles, San Diego
4

1 回答 1

3

使用适当的 HTML 解析器:

from bs4 import BeautifulSoup
soup = BeautifulSoup(open(...).read())
states = {}
for i, table in enumerate(soup("table")):
    for city in table("span"):
        states.setdefault(i, []).append(city.text.strip())

这会给

states
{0: [u'Miami', u'Orlando'], 1: [u'Los Angeles', u'San Diego']}
于 2013-01-30T08:31:10.720 回答