【问题标题】:How do I send text into a textarea through Selenium and Python as per the HTML如何根据 HTML 通过 Selenium 和 Python 将文本发送到文本区域
【发布时间】:2018-07-26 07:03:08
【问题描述】:

无法弄清楚如何将文本写入弹出窗口,这是弹出窗口的样子:

<textarea style="position: absolute; padding: 0px; width: 1px; height: 1em; outline: currentcolor none medium;" autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" wrap="off"></textarea>

这是我尝试使用 XPath 访问它的方式:

driver.find_element_by_xpath("/html/body/div/div[1]/textarea").send_keys("Some text here")

在页面上找不到元素的错误:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div[1]/textarea

我也使用 css_selector 来访问元素,但仍然是同样的错误。 如何正确访问弹出窗口?

这里有更多的 HTML 代码:https://pastebin.com/6jdix2Cm

【问题讨论】:

  • 好像在 iframe 中。你能分享更多关于这个textarea的HTML吗
  • 这里有更多代码pastebin.com/6jdix2Cm。 Textarea 包裹在 iframe 中
  • @Andrew:你能给我们更新吗?任何一个答案有帮助吗?还是您仍然面临任何问题?
  • @cruisepandey 非常感谢它解决了我的问题!

标签: python selenium selenium-webdriver xpath webdriverwait


【解决方案1】:

根据您的回复,此 textarea 位于 iframe 中。

首先你必须切换到框架,然后你可以与这个文本区域进行交互。

要切换到 iframe,您可以使用以下代码:

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@src='https://qsm.qoo10.sg/gmkt.inc.gsm.web/common/scripts/module/tiny_mce_4.5.7/source/plugins/codemirror/source.html']"))  

然后您可以与 textarea 进行交互:

driver.find_element_by_css_selector("textarea[spellcheck='false'][wrap='off'][style$='outline: currentcolor none medium;']").send_keys("Some text here")  

一旦你完成了特定的 iframe,切换到默认内容总是好的。为此,你将需要这段代码:

driver.switch_to.default_content()

希望这会有所帮助。

【讨论】:

  • driver.switch_to.frame() 已弃用且 driver.switch_to.defaultContent() 不是 WebDriver API 的 python 实现
  • @JanRozycki:你说的是哪个版本的硒?我一直在使用 selenium 3.12.0,它运行良好。
  • 除此之外,什么时候python使用驼峰式和分号? ;)
  • @JanRozycki , switch_to.frame() 未被弃用。已弃用的一个是switch_to_frame()
  • @cruisepandey 使用switch_to.default_content() 而不是switch_to.defaultContent();
【解决方案2】:

根据您共享的 HTML,由于 &lt;textarea&gt;&lt;iframe&gt; 内,因此您需要诱导 WebDriverWait 切换到所需的 框架 然后在发送字符序列之前再次诱导 WebDriverWait 使所需的元素可点击,您可以使用以下解决方案:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@src,'gmkt.inc.gsm.web/common/scripts/module/tiny_mce_4.5.7/source/plugins/codemirror/source.html')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.TAG_NAME, "textarea"))).send_keys("Andrew")

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2018-11-13
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多