问题
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?
the code I tried is..(only lines which interact with the page)
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')
error I got:
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:
Try below code :
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 :)
来源:https://stackoverflow.com/questions/45902295/how-to-send-shortcut-keys-using-selenium-in-python-to-move-through-webpage