简体   繁体   English

Python Selenium 无法填写输入字段

[英]Python Selenium can't fill input field

I want to login on a site ( https://gmail.hu ) with selenium, there is a username input field with ID _user and password input field with ID _pass我想用 selenium 登录网站 ( https://gmail.hu ),有一个 ID 为_pass的用户名输入字段和 ID _user的密码输入字段

The password field is a bit tricky because there is two password field you can see if you open the inspector, one is hidden and the other is not.密码字段有点棘手,因为打开检查器可以看到两个密码字段,一个是隐藏的,另一个不是。

<input class="billboard_input" type="password" value="" name="_pass" id="_pass" maxlength="16" style="display: block;"> 

<input class="billboard_input" type="text" value="Jelszó" name="_pass_dummy" id="_pass_dummy" style="display: none;">

I tried to get the element by ID but I can't get it working:我试图通过 ID 获取元素,但无法正常工作:

user = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "_user")))
pw = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "_pass")))

By XPATH I can fill the username input but I can't figure out how can I fill the password input, I tried to send_keys to both password input but nothing happening:通过 XPATH 我可以填写用户名输入但我不知道如何填写密码输入,我尝试将send_keys发送到两个密码输入但没有任何反应:

url = 'https://gmail.hu'
driver.get(url)

user = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/div[1]/form/input[6]")))
pw = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/div[1]/form/div[1]/input[1]")))
pw2 = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/div[1]/form/div[1]/input[2]")))
                
user.send_keys("test")
time.sleep(5)
pw.send_keys("testpw")
time.sleep(5)
pw2.send_keys("testpw")

Here is one way to do it:这是一种方法:

## your imports[...]
import time as t
## browser definition


wait = WebDriverWait(driver, 20)
url = "https://gmail.hu/"
driver.get(url)

cookie_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="ELFOGADOM"]')))
cookie_button.click()
print('accepted cookies')
id_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[id="_user"]')))
id_field.send_keys('viktor_orban')
dummy_password_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[id="_pass_dummy"]')))
dummy_password_field.click()
t.sleep(1)
real_pass_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[id="_pass"]')))
real_pass_field.send_keys('oh well...')
print('sent user & pass')

Result printed in terminal:终端打印结果:

accepted cookies
sent user & pass

Selenium documentation can be found at https://www.selenium.dev/documentation/ Selenium 文档可在https://www.selenium.dev/documentation/找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM