工具: Ubuntu, Python, Selenium, Firefox
我正在尝试自动下载订阅网站上的图像文件。除了通过付费订阅外,我没有其他方法访问服务器。为了避免每个文件下载都需要点击按钮,我决定使用Python、Selenium和Firefox进行自动化。(我已经连续两天第一次使用这三个工具。我也很少了解关于cookies方面的知识。)
我有兴趣按以下三种格式的顺序或优先级下载:['EPS'、'PNG'、'JPG']。网站上有每种格式的下载按钮。
我已经成功地通过手动设置Firefox首选项来自动下载“PNG”和“JPG”文件到磁盘中。这是在这篇文章中建议的: python webcrawler downloading files
然而,当文件是以“EPS”格式时,“您选择了保存”对话框仍然会弹出在Firefox窗口中。
从我的代码中可以看出,我已经将首选项设置为将“EPS”文件保存到磁盘中。(同样,“JPG”和“PNG”文件的保存也正常。)
from selenium import webdriver
profile = webdriver.firefox.firefox_profile.FirefoxProfile()
profile.set_preference("browser.download.folderList", 1)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
'image/jpeg,image/png,application/postscript,'
'application/eps,application/x-eps,image/x-eps,'
'image/eps')
profile.set_preference("browser.helperApps.alwaysAsk.force", False)
profile.set_preference("plugin.disable_full_page_plugin_for_types",
"application/eps,application/x-eps,image/x-eps,"
"image/eps")
profile.set_preference(
"general.useragent.override",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0)"
" Gecko/20100101 Firefox/26.0")
driver = webdriver.Firefox(firefox_profile=profile)
#I then log in and begin automated clicking to download files. 'JPG' and 'PNG' files are
#saved to disk as expected. The 'EPS' files present a save dialog box in Firefox.
我尝试安装了一个名为“download-statusbar”的Firefox扩展程序,据称可以避免出现任何保存对话框。该扩展在Selenium Firefox浏览器中加载,但是它无法正常工作。(许多评论都说这个扩展已经坏了,尽管开发人员坚称它可以工作。)无论如何,它并没有为我工作,所以我放弃了它。
在这次尝试中,我将其添加到了Firefox配置文件中:
#The extension loads, but it doesn't function.
download_statusbar = '/home/$USER/Downloads/'
'/download_statusbar_fixed-1.2.00-fx.xpi'
profile.add_extension(download_statusbar)
从阅读其他stackoverflow.com的文章中,我决定尝试使用urllib2通过url下载文件。根据我的理解,我需要在头文件中添加cookie以便通过url验证下载'EPS'文件。
我对这种技术不熟悉,但这是我尝试直接下载文件的代码。尽管我尝试设置urllib2打开器中的cookies,但它仍然失败并返回“403 Forbidden”的响应。
import urllib2
import cookielib
import logging
import sys
cookie_jar = cookielib.LWPCookieJar()
handlers = [
urllib2.HTTPHandler(),
urllib2.HTTPSHandler(),
]
[h.set_http_debuglevel(1) for h in handlers]
handlers.append(urllib2.HTTPCookieProcessor(cookie_jar))
#using selenium driver cookies, returns a list of dictionaries
cookies = driver.get_cookies()
opener = urllib2.build_opener(*handlers)
opener.addheaders = [(
'User-agent',
'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:26.0) '
'Gecko/20100101 Firefox/26.0'
)]
logger = logging.getLogger("cookielib")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.DEBUG)
for item in cookies:
opener.addheaders.append(('Cookie', '{}={}'.format(
item['name'], item['value']
)))
logger.info('{}={}'.format(item['name'], item['value']))
response = opener.open('http://path/to/file.eps')
#Fails with a 403 Forbidden response
有任何想法或建议吗?我是否错过了一些简单的东西,还是需要放弃自动下载EPS文件的希望?提前感谢。