首页 > 解决方案 > 尝试使用 selenium 自动注册。遇到问题

问题描述

目前正在尝试使用 Selenium 在“mail.com”上自动注册。到目前为止,我已经设法让程序转到 URL。我遇到的问题是,即使我复制了“注册”的完整 XPATH,我也会得到:

" selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/table/tbody/tr[114]/td[2]"}"

错误

这是我目前正在使用的代码:

import selenium
import time
from selenium.webdriver.common.by import By

driver = selenium.webdriver.Chrome(executable_path='pathtochromedriver')
driver.get('https://www.mail.com/')
driver.maximize_window()

# Delay added to allow elements to load on webpage
time.sleep(30)

# Find the signup element
sign_up = driver.find_element_by_xpath('/html/body/table/tbody/tr[114]/td[2]')

标签: pythonselenium

解决方案


尝试使用 ActionsChains 滚动以确保元素在视图中。

from selenium.webdriver.common.action_chains import ActionChains

some_page_item = driver.find_element_by_class_name('some_class')
ActionsChains(driver).move_to_element(some_page_item).click(some_page_item).perform()

还有另一个提示......而不是简单地使用 time.sleep() 来等待元素出现,而是使用 WebDriverWait

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait_for_item = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME ,"some_class_name")))

30 是等待项目出现的秒数;但是,如果它出现在 30 秒之前,那么它将立即继续执行。如果 30 秒过去且该项目未出现,则会发生超时错误。


推荐阅读