在Gmail中找到“新邮件”按钮时,出现“无法找到元素”错误。 Python Slenium Webdriver

时间:2019-06-03 11:00:40

标签: python selenium-webdriver

我是编程新手,我学会了使用Selenium webdriver在Python中自动化web浏览器任务。我正在编写一个程序,该程序登录Gmail,打开一个新的消息窗口并发送电子邮件。我停留在打开新消息窗口的过程中,因为它引发了“无法定位元素”异常。

页面所需部分的html代码为:

<div class="z0"><div class="T-I J-J5-Ji T-I-KE L3" role="button" tabindex="0" jslog="20510; u014N:cOuCgd,Kr2w4b" style="-moz-user-select: none;" gh="cm">Nová zpráva</div></div>

我尝试了多种方法来定位该元素,但所有方法均会失败。这是我尝试过的:

browser.find_element_by_xpath("//div[@class='z0']/div[1]")
browser.find_element_by_class_name('T-I.J-J5-Ji.T-I-KE.L3')
browser.find_element_by_class_name('T-I-KE')     # And other parts of the class
browser.find_element_by_css_selector('.T-I.J-J5-Ji.T-I-KE.L3')
browser.find_element_by_css_selector('.T-I')     # And other parts of the class

登录电子邮件后,用于打开新消息窗口的代码如下:

# Send email of the string.
# Going from logged google accounts screen (https://myaccount.google.com/) to e-mail - this works fine.
menu_elem = browser.find_element_by_class_name('gb_ve')
menu_elem.click()
gmail_elem = browser.find_element_by_id('gb23')
gmail_elem.click()
time.sleep(10)
# Open new message - this is where the exception happens.
new_message_elem = browser.find_element_by_xpath("//div[@id=':3x']/div[2]")
new_message_elem.click()

例外是:

Traceback (most recent call last):
  File "C:/xxx/CommandLineEmailer_cpt11cv1.py", line 35, in <module>
    new_message_elem = browser.find_element_by_xpath("//div[@class='z0']/div[1]")
  File "C:\xxx\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\xxx\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\xxx\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\xxx\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //div[@class='z0']/div[1]

0 个答案:

没有答案