如何在python中使用selenium发送快捷键来浏览网页

时间:2017-08-27 06:33:15

标签: python facebook selenium automation

我希望浏览所有帖子,并在Facebook上点击,我发现我们可以通过键盘上的每个帖子按'j'键和'l'键来点击帖子。现在我想在Python中使用selenium自动化它。 我该如何完成

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

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

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

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') 

希望它会对你有所帮助:)。