硒找不到元素

时间:2019-09-24 14:05:35

标签: python selenium xpath

im试图编写代码以使用硒自动创建gmail。我要查找的项目是以下网址中输入的名字:

https://accounts.google.com/signup/v2/webcreateaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&flowName=GlifWebSignIn&flowEntry=SignUp

我使用了wait,但是它返回TimeoutException错误。 另外,说我想使用隐式等待,该怎么办?

谢谢

class BotCreator:

    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
        self.driver = webdriver.Firefox(executable_path=r'A:\Python Projects\The InstaBOT/geckodriver')

    def shutdown(self):
        self.driver.close

    def gmail_creator(self, n_bots):
        for n in range(n_bots):
            global email
            email = {}
            driver = self.driver
            wait = WebDriverWait(driver, 10)
            driver.get('https://www.google.com/intl/en-GB/gmail/about/')
            driver.find_element_by_xpath('//a[@title="Create an account"]').click()
            wait.until(ec.new_window_is_opened(driver.window_handles))
            after = driver.window_handles[1]
            driver.switch_to.window(after)
            element = wait.until(ec.element_to_be_clickable((By.XPATH, '//input[@id="firstName"]')))
            element.send_keys('awsd')

        return email

gmail_t = BotCreator('John', 'Hoffinsky')
gmail_t.gmail_creator(1)

3 个答案:

答案 0 :(得分:2)

该页面上实际上有几(4)个具有相同XPath的元素。 尝试通过以下XPath使用特定的服务器:

(//a[@title="Create an account"])[1]

您的XPath返回4个具有Chrome扩展名 ChroPath 的元素。


关于隐式等待的问题: 您已经在使用隐式等待。隐式等待设置告诉Selenium轮询指定的时间,直到元素可用。您可以根据需要更改超时时间:

driver.implicitly_wait(15)

link可能会有所帮助。

答案 1 :(得分:1)

单击创建帐户按钮后,它将打开一个用于显示用户详细信息的新窗口。您需要切换到该窗口以访问该元素。请尝试以下代码。

wait = WebDriverWait(driver, 10)
driver.get('https://www.google.com/intl/en-GB/gmail/about/')
driver.find_element_by_xpath('//a[@title="Create an account"]').click()
wait.until(ec.new_window_is_opened(driver.window_handles))
after=driver.window_handles[1]
driver.switch_to.window(after)
element = wait.until(ec.element_to_be_clickable((By.XPATH, '//input[@id="firstName"]')))
element.send_keys('awsd')

浏览器快照:

enter image description here

答案 2 :(得分:0)

使用ID总是比XPath / CSS好

示例

driver.find_element_by_id("FirstName").send_keys("email")