从网站上刮取表格数据

nic*_*las 1 python beautifulsoup web-scraping

我试图使用BeautifulSoup4和Python从网站上刮取表格数据,然后用结果创建一个Excel文档.到目前为止,我有这个:

import urllib2
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://opl.tmhp.com/ProviderManager/SearchResults.aspx?TPI=&OfficeHrs=4&ProgType=STAR&UCCIndicator=No+Preference&Cnty=&NPI=&Srvs=6&Age=All&Gndr=B&SortBy=Distance&ZipCd=78552&SrvsOfrd=0&SpecCd=0&Name=&CntySrvd=0&Plan=H3&WvrProg=0&SubSpecCd=0&AcptPnt=Y&Rad=200&LangCd=99').read())

for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
Run Code Online (Sandbox Code Playgroud)

但它无法显示数据.

有任何想法吗?

kir*_*gin 5

首先,课程StandardResultsGrid不是spad.

其次,你不需要这个tbody东西.只需使用:

for row in soup('table', {'class' : 'StandardResultsGrid'})[0]('tr'):
Run Code Online (Sandbox Code Playgroud)

还要注意,因为在原始页面中包含标题的行tbody由于某种原因包含在内,所以你必须跳过第一行,所以

for row in soup('table', {'class' : 'StandardResultsGrid'})[0]('tr')[1:]
Run Code Online (Sandbox Code Playgroud)

请注意,某些单元格中包含tables,因此您必须td仔细解析s 的内容.