简体   繁体   中英

Selenium not able to find element

Hi guys I'm trying to find an element in a website but for some reason it doesn't let me. The webpage is the login form of Reddit, I try to enter my username and my password but when I list all the inputs it only appears the top search bar. I suppose it is because It's like in another "tab" like that it pops up to the front but I don't know how to manage it. Thanks in advance.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get('https://www.reddit.com')
driver.set_window_size(1200, 1300)

login_button = driver.find_element_by_link_text('Log In')
login_button.click()

username = driver.find_element_by_css_selector('input')
username.send_keys("test code to the form")

Once Login button is clicked an iframe is opened so you first have to switch to that iframe :

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'login')]"))

Also you have a problem is with username = driver.find_element_by_css_selector('input') since input is not an unique css selector.
Try this:

username = driver.find_element_by_css_selector('[id="loginUsername"]')

Also, it would be better to locate the login button as following:

login_button = driver.find_element_by_xpath('//a[contains(@href,"login")]')

Finally, after inserting the username and password don't forget to switch from iframe to default content with

driver.switch_to.default_content()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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