【问题标题】:How can I grab the table data for select rows in BeautifulSoup如何在 BeautifulSoup 中获取选定行的表数据
【发布时间】:2015-07-19 13:09:11
【问题描述】:

我正在尝试以编程方式从该网站上抓取所有表格数据 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 级别工作,但一旦我执行循环要求它查找每一行的所有表数据,我只能取回整个值列表。

【问题讨论】:

  • Datagrid 究竟是什么?
  • 应该是汤的相关选择。

标签: python web-scraping beautifulsoup


【解决方案1】:

页面中有多个表格。如果你检查它们,你会发现你想要的数据在第三个。所以代码可能是:

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]   # Get third table
for tr in tbl.findAll('tr'):     # Get all rows
    for td in tr.findAll('td'):  # Get all cells of row
        if td.p:
            print(td.p.string)

【讨论】:

  • 如果我想通过只调用第一行的数据来测试这个怎么办?对于 tbl.findAll('tr')[1] 中的 tr:使其中断
  • @user3590113:首先,索引为1的元素不是第一个,你应该使用0作为索引。其次,tbl.findAll('tr')[0] 返回单个元素,而不是列表,因此您不能在 for 中使用它。您可以使用tbl.findAll('tr')[0:1] 来创建一个仅包含第一个元素的列表(可迭代)。
  • 如何返回选定的行?让我想显示第三行中的所有值?
  • 我怎样才能抢到一行?例如,如果我想为第三行设置完整的值怎么办?我怎么能得到那个?
  • @user3590113:您可以选择第三行:for tr in tbl.findAll('tr')[2:3]:,然后提取数据:[td.p for for td in tr.findAll('td') if td.p]
猜你喜欢
  • 1970-01-01
  • 2016-11-25
  • 2011-02-16
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多