用漂亮的汤刮js生成的表时出错

Error scraping js generated table with beautiful soup

本文关键字:出错 js 漂亮 汤刮      更新时间:2023-09-26

我正试图使用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                                        ')  

还有,有没有一种更高效、更快的方法可以做到这一点
提前感谢您,如有任何帮助,我们将不胜感激。

几个错误:

  1. 你需要剥去所有的文字。例如,tds[0].text.strip()
  2. 你只写表格的最后一行。ncontent变量在循环过程中被重写

修正错误,你就可以上路了。