【问题标题】:Error scraping js generated table with beautiful soup用漂亮的汤刮 js 生成的表时出错
【发布时间】:2016-04-09 17:15:09
【问题描述】:

我正在尝试使用 Beautiful Soup 和/或 Selenium(没有 pandas,lxml)在 python 2.7 中刮一张桌子。表中的特定列需要写入 csv 文件。我已经查看了大多数类似的问题(1254879330734963,3344897432434378 等),但到目前为止对我没有任何帮助。显然,这是我第一次尝试刮任何东西,所以我什至不假装我理解了我正在做的一半。
下面的代码有点作用:

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                                        ')  

另外,有没有更有效和更快的方法来做到这一点?
提前感谢您 - 任何帮助将不胜感激。

【问题讨论】:

  • 谢谢。对文本进行条带化并在循环中包含文字可以让我获得所有数据。现在我只需要弄清楚如何只写一次标题。

标签: javascript python csv selenium beautifulsoup


【解决方案1】:

几个错误:

  1. 您需要删除所有文本。例如,tds[0].text.strip()
  2. 你只写表格的最后一行。 ncontent 变量在循环期间被重写。

修复错误,一切顺利。

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多