2017-09-15 88 views
0

硒我尝试下载的东西(为了验证它的内容),使用下面的代码作为证据的概念:为什么硒下载不起作用?

from selenium import webdriver 

profile = webdriver.FirefoxProfile() 
#Set Location to store files after downloading. 
profile.set_preference("browser.download.dir", "/tmp") 
profile.set_preference("browser.download.folderList", 2) 

#Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types. 
#profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 
#      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;") 
profile.set_preference("browser.download.manager.showWhenStarting", False) 
profile.set_preference("pdfjs.disabled", True) 
profile.set_preference("browser.helperApps.neverAsk.saveToDisk","application/zip") 
profile.set_preference("plugin.disable_full_page_plugin_for_types", "application/zip") 

browser = webdriver.Firefox(profile) 
browser.implicitly_wait(10) 
browser.get('https://www.thinkbroadband.com/download') 
time.sleep(15) 
elem = browser.find_element_by_xpath('//a[@href="http://ipv4.download.thinkbroadband.com/5MB.zip"]') 
elem.click() 
time.sleep(15) 

然而,没有什么“发生”(即不进行下载),也没有显示错误消息。当我手动点击该下载链接时,测试文件被下载到/tmp

有什么我失踪?

+0

你尝试手动点击链接看是否链接工作? – DebanjanB

+0

@DebanjanB:是的,正在工作,如问题中所述... – Alex

回答

1

问题可能是因为在这种情况下,点击需要经过一个子元素

elem = browser.find_element_by_xpath('//a[@href="http://ipv4.download.thinkbroadband.com/5MB.zip"]/img') 
elem.click() 

但除此之外,当你点击一个链接浏览器在后台为链接检查的东西,该网站似乎有一个问题,当我在浏览器中打开目标链接我得到一个空的响应

Empty response

+0

它不起作用:'selenium.common.exceptions.InvalidSelectorException:消息:给定xpath表达式“// a [@ href =”http:// ipv4.download.thinkbroadband.com/5MB.zip "]/img“无效:SyntaxError:表达式不是合法表达式.' – Alex

+1

你的双引号转换为智能引用,这就是为什么..''''和'” '不一样。而当你在外面使用双引号时,应该使用'''里面的单引号。 '“//a[@href='http://ipv4.download.thinkbroadband.com/5MB.zip']/img”' –

+0

是的,我现在明白了。我与Mac一起工作......似乎总是把它搞砸(因为它是Mac ......)。但它现在似乎工作! – Alex