BeautifulSoup HTML表解析

Ste*_*ner 17 python html-table mechanize beautifulsoup html-parsing

我试图从这个网站解析信息(html表):http://www.511virginia.org/RoadConditions.aspx?j = All&r = 1

目前我正在使用BeautifulSoup,我的代码看起来像这样

from mechanize import Browser
from BeautifulSoup import BeautifulSoup

mech = Browser()

url = "http://www.511virginia.org/RoadConditions.aspx?j=All&r=1"
page = mech.open(url)

html = page.read()
soup = BeautifulSoup(html)

table = soup.find("table")

rows = table.findAll('tr')[3]

cols = rows.findAll('td')

roadtype = cols[0].string
start = cols.[1].string
end = cols[2].string
condition = cols[3].string
reason = cols[4].string
update = cols[5].string

entry = (roadtype, start, end, condition, reason, update)

print entry
Run Code Online (Sandbox Code Playgroud)

问题在于开始和结束列.它们只是打印为"无"

输出:

(u'Rt. 613N (Giles County)', None, None, u'Moderate', u'snow or ice', u'01/13/2010 10:50 AM')
Run Code Online (Sandbox Code Playgroud)

我知道它们存储在列列表中,但似乎额外的链接标记弄乱了原始html的解析,如下所示:

<td headers="road-type" class="ConditionsCellText">Rt. 613N (Giles County)</td>
<td headers="start" class="ConditionsCellText"><a href="conditions.aspx?lat=37.43036753&long=-80.51118005#viewmap">Big Stony Ck Rd; Rt. 635E/W (Giles County)</a></td>
<td headers="end" class="ConditionsCellText"><a href="conditions.aspx?lat=37.43036753&long=-80.51118005#viewmap">Cabin Ln; Rocky Mount Rd; Rt. 721E/W (Giles County)</a></td>
<td headers="condition" class="ConditionsCellText">Moderate</td>
<td headers="reason" class="ConditionsCellText">snow or ice</td>
<td headers="update" class="ConditionsCellText">01/13/2010 10:50 AM</td>
Run Code Online (Sandbox Code Playgroud)

所以应该印刷的是:

(u'Rt. 613N (Giles County)', u'Big Stony Ck Rd; Rt. 635E/W (Giles County)', u'Cabin Ln; Rocky Mount Rd; Rt. 721E/W (Giles County)', u'Moderate', u'snow or ice', u'01/13/2010 10:50 AM')
Run Code Online (Sandbox Code Playgroud)

任何建议或帮助表示赞赏,并提前感谢您.

Ant*_*ins 32

start = cols[1].find('a').string
Run Code Online (Sandbox Code Playgroud)

或者更简单

start = cols[1].a.string
Run Code Online (Sandbox Code Playgroud)

或更好

start = str(cols[1].find(text=True))
Run Code Online (Sandbox Code Playgroud)

entry = [str(x) for x in cols.findAll(text=True)]
Run Code Online (Sandbox Code Playgroud)

  • 欢迎)如果你觉得有帮助,你会接受答案 (21认同)