用漂亮的汤刮js生成的表时出错
Error scraping js generated table with beautiful soup
我正试图使用Beautiful Soup和/或Selenium(没有pandas,lxml)在python 2.7中抓取一个表。表中的特定列需要写入csv文件。我已经研究了大多数类似的问题(1254879330734963、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
变量在循环过程中被重写
修正错误,你就可以上路了。
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- Backbone.js将模型绑定到视图时出错
- 如何解决'窗口未定义'终端上的节点JS出错
- 在节点 js 中使用护照本地模块验证(登录)密码时出错
- 使用Pebble.js获取AJAX请求时出错
- Composer-view.js文件出错
- 将JS项目导入eclipse时出错
- 尝试构建 ember js 项目时出错
- 帆上的自定义和多语言消息如何出错 js.
- Node.js错误:参数太多上传批量数据时出错
- 流星js模板助手导致页面首次加载时出错
- 使用Sequelize.js创建简单PUT请求时出错
- 尝试使用Angular.js显示验证消息时出错
- 安装vertx时出错(vertx运行server.js)
- 解析从js发送到Java的json字符串时出错
- 要求JS 2.1.9引起“;最大调用堆栈"使用Grunt时出错
- 在AngularJS中实现chart.js时出错
- 类型渲染灰尘时出错.js模板
- 可以忽略“加载脚本时出错”js 错误吗?
- 转义字符串用于高亮显示函数时出错(js -regexp)