在Python Selenium中,右键单击href并选择“另存为”

3
我想点击“导出系统”href链接,然后在下拉选项中选择“另存为”。我该怎么做?

<a href="/core/cache/0WDb_ukdMUOA7qoW9lt1cgnee0I=/Exported_Systems.csv" target="_blank">Exported_Systems.csv</a>


这似乎是与http://stackoverflow.com/questions/42717222/right-click-save-as-on-dynamic-href-attribute/42717305#42717305相同的问题。您只需要将“URL”提取到“.csv”文件中吗? - Andersson
href 是动态的,所以我不能直接使用链接来保存文件。 - Sandy
为什么你不能直接使用它?这仍然是同一个链接...分享你已经尝试过但未能获得所需结果的代码。 - Andersson
2个回答

7

这可能不是完美的解决方案,但它可以模拟该工作。您可以使用 actionchains 打开右键菜单。

from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome()
driver.get(link)
elem = driver.find_element_by_css_selector('a[target="_blank"]')
actionChain = ActionChains(driver)
actionChain.context_click(elem).perform()

我使用了"target"属性来选择标签。但现在的问题是访问该菜单超出了selenium的范围。因此,我使用pyautogui模拟了4个向下箭头和回车按钮的按键操作。(4个向下箭头,因为“保存链接”选项在每个锚点标签中都是第4个)

import pyautogui
pyautogui.typewrite(['down','down','down','down','enter'])

希望这可以帮到您。

1
另一种方法是使用配置文件以防止下载对话框出现:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

driver= webdriver.Firefox(profile)
driver.get("yourWebSite")

driver.find_element_by_xpath('//a[@href][text()[contains(., 'Exported_Systems')]]').click()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接