【问题标题】:Python with Selenium: Unable to locate element error带有 Selenium 的 Python:无法找到元素错误
【发布时间】:2017-12-25 07:56:25
【问题描述】:

我正在尝试填充文本框,但无法找到元素。

我已经尝试找到元素

  • 按类别
  • 按名称
  • 增加了 10 秒等待

但我仍然遇到同样的错误。

这里是 HTML

    <div class="innerWrap">
    <textarea aria-autocomplete="list" aria-controls="typeahead_list_u_0_j"
    aria-expanded="false" aria-haspopup="true" aria-label=
    "Write a birthday wish on his Timeline..." class=
    "enter_submit uiTextareaNoResize uiTextareaAutogrow uiStreamInlineTextarea inlineReplyTextArea mentionsTextarea textInput"
    cols="48" id="u_0_k" name="message_text" placeholder=
    "Write a birthday wish on his Timeline..." role="textbox" title=
    "Write a birthday wish on his Timeline..."></textarea>
</div>

我的代码:

textbox =  driver.find_element_by_name('message_text')
textbox.send_keys('Happy Birthday! ')

我正在处理的网页是Facebook Birthdays page

【问题讨论】:

    标签: python html python-3.x selenium


    【解决方案1】:

    这个问题之前已经回答过了,但是答案指向的文档链接已经过时,所以这里是新更新的"switch to"/switch commands selenium docs链接

    您需要使用此命令来切换您的驱动程序,以便它在正确的窗口/框架/等中运行。

    通过运行检查打开了哪些窗口:首先运行driver.getWindowHandles(); 以返回一组所有窗口

    然后使用driver.switchTo().window(handle);} #if switching to another window

    driver.switchTo().frame("yourframename");} #if switching to a frame

    driver.switchTo().alert(); #if switching to a popup

    希望对你有帮助

    A similar question

    【讨论】:

    • 我确实最终成功地找到了元素,但通过不同的方法。我尝试更改窗口和框架,但这并没有帮助,因为我已经在同一个窗口中并且代码中没有 iframe。所以我通过driver.page_source 下载了页面源,我想在下载的源中定位的元素的名称实际上是“message”而不是“message_text”。但是,当我通过检查元素在浏览器中检查此元素的名称时,它仍然显示“message_text”。我不确定为什么元素名称会有所不同。
    • @AbdulMoizFarooq 这是一个有趣的发现。您应该将其发布为帮助其他人的答案。感谢您的更新。
    【解决方案2】:

    所以我终于能够通过查看页面源找到元素并修复上述错误。

    print(driver.page_source)
    

    页面源显示元素的名称是 message 而不是 message_text。但是浏览器中的检查元素仍然显示message_text

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2022-07-28
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 2021-05-18
      • 2018-08-01
      相关资源
      最近更新 更多