用硒查找元素等

时间:2019-08-18 21:22:03

标签: python selenium

我在WIN 10上并使用Python 3.7。我正在尝试登录以下页面,但找不到元素:

https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin&hl=en-GB

以下是我尝试过的内容:

import requests
from selenium import webdriver


driver = webdriver.Firefox()
url_google = "https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin&hl=en-GB"
driver.get(url_google)

driver.find_element_by_class_name("Xb9hP").send_keys("1234")
driver.find_element_by_link_text ("Email or phone").send_keys("1234")
driver.find_element_by_css_selector("div.Xb9hP").send_keys("1234")
driver.find_element_by_css_selector("input.email").send_keys("1234")
driver.find_element_by_xpath("//Xb9hP[1]")
driver.find_element_by_xpath("//form[@method='post']")
driver.find_element_by_id("InputEmail").send_keys("1234")
driver.find_element_by_id("InputPassword").send_keys("1111")

可以让我知道我将使用什么吗?为了让我更好地理解Selenium,我将欣赏如何使用每个函数发送“ 1234”的示例,例如:

find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

谢谢。

3 个答案:

答案 0 :(得分:2)

避免在此字段上使用类名,因为它似乎是动态生成的。请研究硒等待。

答案 1 :(得分:1)

您可以通过id查找元素,我建议添加WebDriverWait以确保该元素可见。尝试以下代码:

url_google = "https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin&hl=en-GB"
driver.get(url_google)
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'identifierId')))
driver.find_element(By.ID, 'identifierId').send_keys('1234')

答案 2 :(得分:1)

在这种情况下,

使用LinkText和ID应该可以。

driver.find_element_by_link_text ("Email or phone").send_keys("1234")
driver.find_element_by_id("InputPassword").send_keys("1111")

尝试对每个元素使用显式等待。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
# wait for element to appear, then hover it
wait = WebDriverWait(driver, 10)
element = wait.until(ec.visibility_of_element_located(By.Id, "InputPassword"))