将密钥发送到文本区域,在 Python 中使用 Selenium 不起作用



>im 试图通过制作一个进入 Instagram 帐户并对帖子发表评论的机器人来学习硒

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
site = webdriver.Edge('C:\P\Automation\MicrosoftWebDriver')
site.get('https://www.instagram.com/example_account/')
ref = site.find_element_by_xpath("//*[@id="reactroot"]/section/main/div/div/article/div[1]/div/div[1]/div[1]/a")
site.get(ref.get_attribute('href'))
txt = site.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/article/div[2]/section[3]/form/textarea')
txt.send_keys('test')
txt.send_keys(Keys.ENTER)

问题是当我将键发送到注释元素时

<textarea aria-label="Add a comment…" placeholder="Add a comment…" class="Ypffh" autocomplete="off" autocorrect="off" style="height: 18px;"></textarea>

第一次我尝试发送密钥时间,第二次运行命令时,它什么都不做:

txt.send_keys('test')

它给了我一条错误消息:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:PythonPython37-32libsite-packagesseleniumwebdriverremotewebelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "C:PythonPython37-32libsite-packagesseleniumwebdriverremotewebelement.py", line 628, in _execute
return self._parent.execute(command, params)
File "C:PythonPython37-32libsite-packagesseleniumwebdriverremotewebdriver.py", line 320, in execute
self.error_handler.check_response(response)
File "C:PythonPython37-32libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: Stale element reference

希望得到一些帮助,谢谢!

在此之前sendkeys()使用click()方法在文本区域内单击,然后尝试插入文本。

基于您的解决方案,对我有用的是使用不同的选择器调用文本区域:

textarea = site.find_element_by_xpath('//textarea')
textarea.click()
textarea2 = site.find_element_by_tag_name('textarea')
textarea2.send_keys('hi!')

(相同的选择器不起作用(

好吧,我发现了问题,问题是当将键发送到文本区域时,元素会从中更改:

<textarea class="Ypffh" aria-label="Add a comment…" placeholder="Add a comment…" autocomplete="off" autocorrect="off"></textarea>

对此:

<textarea class="Ypffh" style="height: 19px;" aria-label="Add a comment…" placeholder="Add a comment…" autocomplete="off" autocorrect="off"></textarea>

这就是为什么

过时元素引用

出现错误。

我的解决方案是选择元素,发送密钥,然后再次选择它并再次发送密钥,如下所示:

txt = site.find_element_by_class_name('Ypffh')
txt.send_keys('test')
txt = site.find_element_by_class_name('Ypffh')
txt.send_keys('test')
txt.send_keys(Keys.ENTER)

(我改变了查找元素的方式,因为按类名查找它在代码中看起来要好得多(

如果有人有更好的解决方案,我将很高兴听到!

最新更新