如何在python中使用Selenium发送快捷键以浏览网页 [英] How to send shortcut keys using selenium in python to move through webpage

查看:54
本文介绍了如何在python中使用Selenium发送快捷键以浏览网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历所有帖子,然后像在Facebook上一样点击,我发现我们可以遍历所有帖子,同时按下键盘上的"j"键和"l"键即可喜欢该帖子.现在,我想在Python中使用Selenium来自动执行此操作.我该怎么做?

I want to move through the all the posts and hitting like on the Facebook, and what I found out is we can move through every post pressing 'j' key on the keyboard and 'l' key to like the post. Now I want to automate this using selenium in Python. how can I accomplish this?

我尝试的代码是..(仅与页面交互的行)

page=driver.find_element_by_tag_name('body')
for i in range(10):#i am testing this so i tried to do this for 10 posts
time.sleep(2)
page.send_keys('j')
time.sleep(2)
page.send_keys('l')

我遇到的错误:

 File "C:/Users/py/PycharmProjects/webscarping/seliim2.py", line 23, in <module>
page.send_keys('j')
File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 350, in send_keys
'value': keys_to_typing(value)})
File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 499, in _execute
return self._parent.execute(command, params)
File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 297, in execute
self.error_handler.check_response(response)
File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <body class="fbIndex UIPage_LoggedOut _-kb _61s0 b_c3pyn-ahh gecko win x1 Locale_en_GB"> stale: either the element is no longer attached to the DOM or the page has been refreshed

推荐答案

尝试以下代码:

from selenium.webdriver.common.keys import Keys

driver.find_element_by_tag_name('body').send_keys(Keys.ARROW_DOWN + 'j') 

driver.find_element_by_tag_name('body').send_keys(Keys.ARROW_DOWN + 'l') 

希望它会为您提供帮助:)

Hope it will help you :)

这篇关于如何在python中使用Selenium发送快捷键以浏览网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆