使用Python/Selenium刮擦动态/ Javascript生成的网站

Kar*_*ren 3 python selenium

我正在试图抓住这个网站:

http://stats.uis.unesco.org/unesco/TableViewer/tableView.aspx?ReportId=210

使用Python和Selenium(参见下面的代码).内容是动态生成的,显然未加载浏览器中不可见的数据.我尝试使浏览器窗口变大,并滚动到页面底部.扩大窗口可以获得我想要的所有水平方向数据,但仍有大量数据需要在垂直方向上进行刮擦.滚动似乎根本不起作用.

有没有人对如何做到这一点有任何好主意?

谢谢!

from selenium import webdriver
import time

url = "http://stats.uis.unesco.org/unesco/TableViewer/tableView.aspx?ReportId=210"
driver = webdriver.Firefox()
driver.get(url)
driver.set_window_position(0, 0)
driver.set_window_size(100000, 200000)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

time.sleep(5) # wait to load

soup = BeautifulSoup(driver.page_source)

table = soup.find("table", {"id":"DataTable"})

### get data
thead = table.find('tbody')
loopRows = thead.findAll('tr')
rows = []
for row in loopRows:
rows.append([val.text.encode('ascii', 'ignore') for val in  row.findAll(re.compile('td|th'))])
with open("body.csv", 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for row in rows:
      file_writer.writerow(row)
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 5

这将使您将整个csv自动保存到磁盘,但我还没有找到一种可靠的方法来确定下载完成的时间:

import os
import contextlib
import selenium.webdriver as webdriver
import csv
import time

url = "http://stats.uis.unesco.org/unesco/TableViewer/tableView.aspx?ReportId=210"
download_dir = '/tmp'
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.dir", download_dir)
# 2 means "use the last folder specified for a download"
fp.set_preference("browser.download.folderList", 2)
fp.set_preference("browser.download.manager.showWhenStarting", False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-csv")

# driver = webdriver.Firefox(firefox_profile=fp)
with contextlib.closing(webdriver.Firefox(firefox_profile=fp)) as driver:
    driver.get(url)
    driver.execute_script("onDownload(2);")
    csvfile = os.path.join(download_dir, 'download.csv')

    # Wait for the download to complete
    time.sleep(10)
    with open(csvfile, 'rb') as f:
        for line in csv.reader(f, delimiter=','):
            print(line)
Run Code Online (Sandbox Code Playgroud)

说明:

将浏览器指向url.您将看到有一个Actions菜单,其中包含选项Download report data...和子选项"Comma-delimited ASCII format (*.csv)".如果你检查这些单词的HTML,你会发现

"Comma-delimited ASCII format (*.csv)","","javascript:onDownload(2);"
Run Code Online (Sandbox Code Playgroud)

因此,您可能会尝试webdriver执行JavaScript函数调用onDownload(2).我们可以做到这一点

driver.execute_script("onDownload(2);")
Run Code Online (Sandbox Code Playgroud)

但通常会弹出另一个窗口,询问您是否要保存文件.为了自动保存到磁盘,我使用了本FAQ中描述的方法.棘手的部分是找到在此行上指定的正确MIME类型:

fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-csv")
Run Code Online (Sandbox Code Playgroud)

curlFAQ中描述的方法在这里不起作用,因为我们没有csv文件的url.但是,此页面描述了查找MIME类型的另一种方法:使用Firefox浏览器打开保存对话框.选中"为此类文件自动执行此操作"复选框.然后检查~/.mozilla/firefox/*/mimeTypes.rdf最近添加的描述的最后几行:

  <RDF:Description RDF:about="urn:mimetype:handler:application/x-csv"
                   NC:alwaysAsk="false"
                   NC:saveToDisk="true">
    <NC:externalApplication RDF:resource="urn:mimetype:externalApplication:application/x-csv"/>
  </RDF:Description>
Run Code Online (Sandbox Code Playgroud)

这告诉我们mime类型是"application/x-csv".宾果,我们在做生意.