【发布时间】:2012-06-13 14:36:29
【问题描述】:
我正在为 Python 2.7 使用 selenium webdriver:
启动浏览器:
browser = webdriver.Firefox()。转到某个网址:
browser.get('http://www.google.com')。
此时,如何向浏览器发送“另存为”命令?
注意:这不是我感兴趣的网页源。我想使用实际的“将页面另存为”Firefox 命令保存页面,这会产生与保存网页源不同的结果。
【问题讨论】:
我正在为 Python 2.7 使用 selenium webdriver:
启动浏览器:browser = webdriver.Firefox()。
转到某个网址:browser.get('http://www.google.com')。
此时,如何向浏览器发送“另存为”命令?
注意:这不是我感兴趣的网页源。我想使用实际的“将页面另存为”Firefox 命令保存页面,这会产生与保存网页源不同的结果。
【问题讨论】:
如果您使用的是 Linux,则可以使用 xte。安装
sudo apt-get install xautomation
首先。
from subprocess import Popen, PIPE
save_sequence = """keydown Control_L
key S
keyup Control_L
"""
def keypress(sequence):
p = Popen(['xte'], stdin=PIPE)
p.communicate(input=sequence)
keypress(save_sequence)
【讨论】:
很遗憾,您无法使用 Selenium 做您想做的事情。您可以使用 page_source 来获取 html,但仅此而已。
遗憾的是,Selenium 无法与您保存为时提供给您的对话框交互。
您可以执行以下操作来启动对话框,但随后您将需要 AutoIT 之类的工具来完成它
from selenium.webdriver.common.action_chains import ActionChains
saveas = ActionChains(driver).key_down(Keys.CONTROL)\
.send_keys('s').key_up(Keys.CONTROL)
saveas.perform()
【讨论】:
我也遇到过类似的问题,最近解决了:
@AutomatedTester 给出了一个不错的答案,但是他的答案并没有一路解决问题, 您仍然需要自己再按一次 Enter 才能完成这项工作。
因此,我们需要 Python 为我们再按一次 Enter。
在以下线程中关注@NoctisSkytower 的回答:
复制他对类的定义,然后将以下内容添加到@AutomatedTester 的答案中:
SendInput(Keyboard(VK_RETURN))
time.sleep(0.2)
SendInput(Keyboard(VK_RETURN, KEYEVENTF_KEYUP))
您可能还想查看以下链接:
How can selenium web driver get to know when the new window has opened and then resume its execution
你可能会遇到弹出窗口,这个帖子会告诉你想做什么。
【讨论】: