[英]Error scraping js generated table with beautiful soup
我正在尝试使用Beautiful Soup和/或Selenium(no pandas,lxml)在python 2.7中刮一张表。 该表中的特定列需要写入csv文件。 我已经看了大部分类似的问题( 12548793 , 30734963, 33448974 , 32434378和更多),但没有为我工作至今。 显然,这是我第一次尝试刮擦任何东西,所以我什至不假装自己了解自己所做的一半。
下面的代码有些起作用:
import urllib2
import bs4
from bs4 import BeautifulSoup
import csv
url = "http://data.dnr.nebraska.gov/RealTime/Gage/Index?StationSource=1&StationType=3&RiverBasin="
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, "html.parser")
#get table headers for the columns of interest
#Data of interest:['Station_Name', 'Station_number', 'Date_time', 'Stage', 'Discharge'])
table1 = soup.find("table", id="StationNames")
ths = table1.findAll('th')
headers = (ths[0].text, ths[1].text, ths[2].text, ths[3].text, ths[4].text)
#print headers
#get measurements
table = soup.find_all('table', {"class":"btn-NDNR BlueUnderline"})
for tr in soup.find_all('tr')[2:]:
tds = tr.find_all('td')
ncontent =(tds[0].text, tds[1].text, tds[2].text, tds[3].text, tds[4].text)
#print ncontent
#write the csv file
with open('E:/test/nebraska.csv', 'a') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
writer.writerow(ncontent)
#writer.writerow([value.get_text(strip=True).encode("utf-8") for value in ncontent])
除了csv表是空的,而且在我打印时,这是我得到的:
(u'\r\n Station Name\r\n ', u'\r\n Station Number\r\n ', u'\r\n Date Time (UTC)\r\n ', u'\r\n Stage\r\n ', u'\r\n Discharge\r\n ')
(u'\nBig Blue River at Beatrice - NDNR ', u'\r\n 6881500\r\n ', u'\r\n 01/05/2016 14:45 \r\n ', u'\r\n 4.27\r\n ', u'\r\n 524.62\r\n ')
另外,是否有更有效,更快捷的方法来执行此操作?
预先谢谢您-任何帮助将不胜感激。
几个错误:
tds[0].text.strip()
ncontent
变量。 修正错误,您将一路顺风。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.