如何获取BeautifulSoup中选定行的表数据

时间:2015-07-19 13:09:11

标签: python web-scraping beautifulsoup

我正在尝试以编程方式抓取此网站上的所有表格数据 http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8

理想情况下,这将逐行进行。因此,例如,我可以说获取每一行的所有表数据,然后能够跳过特定的行。

  from bs4 import BeautifulSoup
import requests

r=requests.get('http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8')
soup=BeautifulSoup(r.content,'lxml')

data = []
info = {}
DataGrid=soup.find('table')
for tr in DataGrid.find_all('tr')[1:]:
    for td in tr.find_all('td')[0]:
            info['Name']=td
    for td in tr.find_all('td')[1]:
            info['City']=td
    for td in tr.find_all('td')[2]:
            td=td.strip().replace(',','')
            info['Phone']=td
    for td in tr.find_all('td')[3]:
            info['more']=td
            data.append(info)

我尝试过切片,虽然它似乎在tr级别工作,但是一旦我执行循环要求它查找每一行的所有表数据,我只能返回整个值列表。< / p>

1 个答案:

答案 0 :(得分:0)

页面中有多个表格。如果您全部检查它们,您会发现所需的数据位于第三个数据中。所以代码可以是:

from bs4 import BeautifulSoup
import requests

r=requests.get('http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8')
soup=BeautifulSoup(r.content)

tbl = soup.findAll('table')[2]
for tr in tbl.findAll('tr'):
    for td in tr.findAll('td'):
        if td.p:
            print td.p.string