Python硒-使用browser.find_element_by_id找不到ID为

问题描述

我对硒有一些问题。我是Selenium,W​​eb抓取和python整体的新手。我正在做一个练习项目,可以直接从IDE发送电子邮件

我已经能够很好地在“发送到”,“抄送”和“主题行”中输入内容。输入正文时遇到问题。

这是我的电子邮件/检查元素的屏幕截图:

Here is a screenshot of my email/inspect element

您可以在这图片中看到(由stackOverflow像素化,但是我想您可以理解,主体是一个ID为“ tinymce”的大盒子。代表此文本输入的代码块为:

<body id="tinymce" class="mce-content-body mce-inactive-editor" data-id="ZmHtmlEditor1_body" 
contenteditable="true" style="font-family: arial,helvetica,sans-serif; font-size: 10pt; color: rgb(0,0); width: 696px; height: 212px;" data-mce-style="font-family: arial,sans-serif; font-
size: 10pt; color: #000000;" dir="LTR" aria-label="Compose body"><div><br data-mce-bogus="1"></div>
</body>

我的代码(用于打开文本框)是

# EMAIL BODY TEXT
content = pyit.inputStr(prompt='What is the body of your email?\n')

clickBodyText = browser.find_element_by_id('tinymce').click()
bodyText = browser.find_element_by_id('tinymce').sendKeys(content)

我首先单击正文,以使输入处于活动状态,然后单击内容的sendkey。这将返回没有此类元素错误

    selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="tinymce"]"}
  (Session info: chrome=84.0.4147.125)

解决方法

要在元素中发送字符序列,您必须为element_to_be_clickable()引入WebDriverWait,并且可以使用以下任一Locator Strategies:>

  • 使用CSS_SELECTOR

    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"body.mce-content-body.mce-inactive-editor#tinymce"))).sendKeys(content)
    
  • 使用XPATH

    WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//body[@class='mce-content-body mce-inactive-editor' and @id='tinymce']"))).sendKeys(content)
    
  • 注意:您必须添加以下导入:

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

您可以使用

find_element_by_id()

find_element_by_xpath()

,但是如果在执行命令之前未加载元素,则错误将相同 为此,您可以使用下面的方法

import time
time.sleep(5)

打开网页后使用time.sleep,以便可以在执行任何操作之前将其完全加载