我正在尝试在Gmail创建页面中填写表格。但是由于某种原因,我的驱动程序找不到代码。我已经使用了所有选项,路径,ID,名称,类名,但是没有任何作用
chrome_driver = './chromedriver'
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver)
driver.get('https://www.google.com/intl/nl/gmail/about/#')
try:
print('locating create account button')
create_account_button = driver.find_element_by_class_name('h-c-button')
except:
print("error, couldn't find create account button")
try:
create_account_button.click()
print('navigating to creation page')
except:
print('error navigating to creation page')
time.sleep(15)
first_name_form = driver.find_element_by_class_name('whsOnd zHQkBf')
(睡眠只是暂时的,以确保完全加载,我知道效率不高)
这是我得到的错误:
Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"css
selector","selector":".whsOnd zHQkBf"}
(Session info: chrome=81.0.4044.129)
感谢您的帮助
答案 0 :(得分:1)
我发现了您的错误,并且为您提供了解决方案。首先让我向您确定问题。当您单击“创建新帐户”时,将打开一个新窗口。但是您的漫游器仍然无法确定您位于第一个窗口中(在您单击第一个按钮以创建帐户的窗口中)。因此,机器人试图查看是否有名字输入。这就是失败的原因。因此,解决方案是您必须更改要指定的窗口。您可以通过以下方式将其完成:
代码
from selenium import webdriver
import time
path = '/home/avionerman/Documents/stack'
driver = webdriver.Firefox(path)
driver.get('https://www.google.com/intl/nl/gmail/about/#')
try:
print('locating create account button')
create_account_button = driver.find_element_by_class_name('h-c-button')
except:
print("error, couldn't find create account button")
try:
create_account_button.click()
print('navigating to creation page')
except:
print('error navigating to creation page')
time.sleep(15)
# Keeping all the windows into the array named as handles
handles = driver.window_handles
# Keeping the size of the array in order to know how many windows are open
size = len(handles)
# Switch to the second opened window (id:1)
driver.switch_to.window(handles[1])
# Print the title of the current page in order to validate if it's the proper one
print(driver.title)
time.sleep(10)
first_name_input = driver.find_element_by_id('firstName')
first_name_input.click()
first_name_input.send_keys("WhateverYouWant")
last_name_input = driver.find_element_by_id('lastName')
last_name_input.click()
last_name_input.send_keys("WhateverYouWant2")
username_input = driver.find_element_by_id('username')
username_input.click()
username_input.send_keys('somethingAsAUsername')
pswd_input = driver.find_element_by_name('Passwd')
pswd_input.click()
pswd_input.send_keys('whateveryouwant')
pswd_conf_input = driver.find_element_by_name('ConfirmPasswd')
pswd_conf_input.click()
pswd_conf_input.send_keys('whateveryouwant')
time.sleep(20)
因此,如果您转到第21行,您会看到我有一些评论,目的是告诉您这些行(从21到31)在做什么。
此外,我为您插入了所有需要的代码(名字,姓氏等)。您只需找到创建按钮(最后一个)。
注意:在这种情况下,请尝试使用ID,而不要像我已经为您使用的那样使用类名(当ID清晰且唯一)。