我正在尝试按Ctrl+s,然后单击网页上的enter以保存其html。但是按键功能不起作用。我尝试过方式1和方法2,但都不起作用。但是,如果我在执行action.send_keys('s')
之前不执行action.key_down(Keys.CONTROL)
,那么它可以正常工作。这是我的完整代码:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome(executable_path="chromedriver.exe")
# get method to launch the URL
driver.get("https://www.google.ca/")
time.sleep(3)
action = ActionChains(driver)
# click google search bar (to make sure driver is working)
driver.find_element_by_name("q").click()
print("passed1")
time.sleep(3)
# way 1
action.key_down(Keys.CONTROL).send_keys('s').key_up(Keys.CONTROL).perform()
print("passed2")
# way 2
action.key_down(Keys.CONTROL)
action.send_keys('s')
action.key_up(Keys.CONTROL)
action.perform()
print("passed2")
time.sleep(100)
driver.close()
有人能向我解释一下他的问题吗?我已经想了一个小时了。
环顾四周后,我发现不建议为此目的与浏览器进行交互。最好是得到page_source
。
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r"C:Program Files (x86)Seleniumchromedriver.exe")
driver.get("http://www.example.com")
with open('page.html', 'w', encoding='utf-8') as f:
f.write(driver.page_source)