Selenium with Python: send_keys() doesn't work

2019-07-29 10:54发布

I am using python Selenium, with headless ubuntu at digitalocean, which has headless Chrome on it. I used

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

at senium.webdriver.common.keys

But it doesn't work.

I imported everything needed, with no python syntax error, and ran successfully, but tabs are not switched with my code.

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

also doesn't work. The same code can switch between tabs on my local computer, which has physical keyboard and monitor. Btw, I used pyvirtualdisplay with my headless Chrome.

I suspect that using headless Ubuntu and headless Chrome on it may cause this problem. I guess headless Ubuntu can' t send keys, as the code above directed.

How can I make my remote, headless Ubuntu send keys to the browser?

1条回答
狗以群分
2楼-- · 2019-07-29 11:54

This is well-known issue of chromedriver. Comment from Chromium developer's team

This is a limitation in the way we simulate keyboard input in ChromeDriver. Keys get sent directly to the render process, bypassing the browser process. So any keyboard shortcut handlers in the browser process will not be invoked by sendKeys().

You can use following code instead:

driver.execute_script("window.open('url_of_page_to_get', 'new_window')")

This will allow you to open URL in new tab

P.S. Please mark this answer as "Accepted" if it solved your problem or let me know in case of issues

查看更多
登录 后发表回答