我正在试图抓住这个网站:
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)
解决方法:
这将使您将整个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)
说明:
将浏览器指向url.
您将看到有一个“操作”菜单,其中包含“下载报告数据”选项以及一个名为“逗号分隔的ASCII格式(* .csv)”的子选项.如果你检查这些单词的HTML,你会发现
"Comma-delimited ASCII format (*.csv)","","javascript:onDownload(2);"
因此,您可能会尝试让webdriver执行JavaScript函数调用onDownload(2).我们可以做到这一点
driver.execute_script("onDownload(2);")
但通常会弹出另一个窗口,询问您是否要保存文件.为了自动保存到磁盘,我使用了this FAQ中描述的方法.棘手的部分是找到要在此行指定的正确MIME类型:
fp.set_preference("browser.helperApps.neverAsk.savetodisk", "application/x-csv")
FAQ中描述的curl方法在这里不起作用,因为我们没有csv文件的url.但是,this page描述了另一种查找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>
这告诉我们mime类型是“application / x-csv”.宾果,我们在做生意.