如何获取 BeautifulSoup 中 select 行的 table 数据
How can I grab the table data for select rows in BeautifulSoup
我正在尝试以编程方式从该网站抓取所有 table 数据
http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8.
理想情况下,这将逐行进行。因此,例如,我可以说获取每行的所有 table 数据,然后能够跳过特定行。
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 级别工作,但一旦我执行循环要求它为每一行找到所有 table 数据,我只能取回整个列表值。
页面中有多个表格。如果您检查所有这些,您会发现您想要的数据在第三个中。所以代码可以是:
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)
我正在尝试以编程方式从该网站抓取所有 table 数据 http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8.
理想情况下,这将逐行进行。因此,例如,我可以说获取每行的所有 table 数据,然后能够跳过特定行。
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 级别工作,但一旦我执行循环要求它为每一行找到所有 table 数据,我只能取回整个列表值。
页面中有多个表格。如果您检查所有这些,您会发现您想要的数据在第三个中。所以代码可以是:
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)