Getting error message with using find_element_by_name from Selenium - python-3.x

I am using selenium to automate few tasks. My code till now just opens browser and gets username and password to fill them later but find_element_by_name is not working properly.
from selenium import webdriver
import time
driver = webdriver.Chrome(r'C:\Users\tarek\Desktop\namshi\chromedriver.exe')
driver.get("https://my.namshi.com/")
time.sleep(5)
try:
username = driver.find_element_by_name('email')
password = driver.find_element_by_name('password')
print(username)
except:
print('failed')

Why would you need to get the password or email? Do you mean you want to click on the fields and fill them with the two queries? If so, then you need to call the click method on your username and password because the find_element_by_name function returns a web element instead of finding it (which would be way more convenient, to be honest)
Basically:
def log_in(email, password) -> Webelement (a class):
username = driver.find_element_by_name('email')
username.click()
username.send_keys(email, Keys.RETURN)
password = driver.find_element_by_name('password')
password.click()
password.send_keys(password, Keys.RETURN)
try:
log_in()
except:
print('failed')

You have at least three elements with name email, I have tried this XPath:
//*[#name='email']
Your element is the second one I guess:
(//input[#name='email'])[2]

Related

I'm writing a code where I can enter Instagram and get the follower list

Hello ı'm a beginner coder
I want to login to instagram using selenium and get my follower list but my code But the code I wrote does not give any error or output.
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
class İnstagram:
def __init__(self,name,password):
self.browser = webdriver.Firefox()
self.username = username
self.password = password
def signIn(self):
self.browser.get("https://www.instagram.com")
time.sleep(1)
name = self.browser.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[1]/div/label/input").send_keys(self.username)
psw = self.browser.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[2]/div/label/input").send_keys(self.password)
self.browser.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[3]").click()
time.sleep(7)
def getFollowers(self):
self.browser.get("https://www.instagram.com/emirhaninmalikanesi/followers/")
followers = self.browser.find_elements(By.CSS_SELECTOR,"._ab8w._ab94._ab99._ab9h._ab9m._ab9o._abcm")
for user in followers:
name = user.find_element(By.CSS_SELECTOR,".x1i10hfl.xjbqb8w.x6umtig.x1b1mbwd.xaqea5y.xav7gou.x9f619.x1ypdohk.xt0psk2.xe8uvvx.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x16tdsg8.x1hl2dhg.xggy1nq.x1a2a7pz.notranslate._a6hd").get_attribute("href")
print(name)
instagram = İnstagram(username,password)
instagram.signIn()
instagram.getFollowers()
Your code has two flaws
Before login you have to close the cookies dialog, otherwise the code raises ElementClickInterceptedException when trying to click on "Log in".
No use of selenium built-in timeout methods (driver.implicitly_wait or WebDriverWait) to wait for an element to be found. This causes followers to be an empty list.
Corrected code
driver.implicitly_wait(9) # driver waits up to 9 seconds for an element to be found
driver.find_element(By.XPATH,"//div[#role='dialog']/div/button[contains(.,'cookie')]").click()
driver.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[1]/div/label/input").send_keys(username)
driver.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[2]/div/label/input").send_keys(password)
driver.find_element(By.XPATH,"//*[#id='loginForm']/div[1]/div[3]").click()
driver.get("https://www.instagram.com/emirhaninmalikanesi/followers/")
followers = driver.find_elements(By.CSS_SELECTOR,"._ab8w._ab94._ab99._ab9h._ab9m._ab9o._abcm")
for user in followers:
name = user.find_element(By.CSS_SELECTOR,".x1i10hfl.xjbqb8w.x6umtig.x1b1mbwd.xaqea5y.xav7gou.x9f619.x1ypdohk.xt0psk2.xe8uvvx.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x16tdsg8.x1hl2dhg.xggy1nq.x1a2a7pz.notranslate._a6hd").get_attribute("href")
print(name)
As a final consideration, notice that you can avoid the login process by loading in selenium a user profile where you are already logged in. For more info look here https://stackoverflow.com/a/75434260/8157304

How to fix selenium "Message: no such element: Unable to locate element

I need to fix my script I'm still geting the error:
no such element found
Part of my code is:
driver = webdriver.Chrome(r'C:\\chromedriver_win32\\chromedriver.exe')
driver.get("http://bulksmsplans.com/register")
# find username/email field and send the username itself to the input field
country_input = driver.find_element(By.NAME, "country_id")
select_object = Select(country_input)
select_object.select_by_value(country_id)
# find password input field and insert password as well
name_input = driver.find_element(By.NAME, "name")
time.sleep(2)
name_input.send_keys(name)
email_input = driver.find_element(By.NAME, "email")
time.sleep(2)
email_input.send_keys(email)
phone_input = driver.find_element(By.NAME, "phone")
phone_input.send_keys(phone)
time.sleep(2)
WebDriverWait(driver, 20).until(
EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[title='reCAPTCHA']")))
WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "div.recaptcha-checkbox-border"))).click()
button = driver.find_element(By.XPATH, "//input[#type='submit']")
button.click();
All working, but the last step when the bot must to click on green button "Create Account", nope...
What is wrong on this line:
button = driver.find_element(By.XPATH, "//input[#type='submit']")
Thanks
While interacting with the reCAPTCHA you have switched to the <iframe>.
Next, to click on the element Create Account you have to shift Selenium's focus back to the default content (or parent_frame) using either of the following lines of code:
Using default_content():
driver.switch_to.default_content()
Using parent_frame():
driver.switch_to.parent_frame()

Unable to click sign in/out button using python selenium

I'm trying to create a code where I can auto sign in and sign out on HR Portal i.e. "https://newage.greythr.com/". However, I'm unable to click the sign in/out button after logging in. Initial part of the code is working fine but the bottom part i.e. # Sign in/out is giving InvalidArgumentException error. I've tried 2 alternatives both mentioned below in the code but none of it is executing and giving the same error. Also, I tried to increase the wait time still it failed.
If anything is required from my end kindly let me know in comments section.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium import webdriver
driver = webdriver.Chrome(executable_path='C:/Users/Selenium Drivers/chromedriver.exe')
# Open the website
driver.get("https://newage.greythr.com/")
time.sleep(2)
# Defining username & password
username = "****"
password = "****"
time.sleep(2)
# Entering username
user = driver.find_element("id", "username")
user.click()
user.send_keys(username)
time.sleep(2)
# Entering password
psw = driver.find_element("id", "password")
psw.click()
psw.send_keys(password)
time.sleep(2)
# Click login button
driver.find_element("id", "password").submit()
# Sign in/out
time.sleep(10)
driver.find_element("XPATH", "//button[contains(.,'Sign In')]").click()
**Upper part is same as above**
# Sign in/out
sign = driver.find_element("XPATH", "/html/body/app/ng-component/div/div/div[2]/div/ghr-home/div[2]/div/gt-home-dashboard/div/div[2]/gt-component-loader/gt-attendance-info/div/div/div[3]/gt-button[1]")
time.sleep(20)
sign.click()
You should be using 'xpath' argument or import the By module and do it like
from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, "//button[contains(.,'Sign In')]").click()

Find the Twitter text box element with python selenium

I made my own Twitter complaint bot that tweets at my ISP if the network drops.
Code works perfect, until it has to find the Twitter textbox to type the tweet.
Main error is:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
I have tried:
Adding time delays
Using Firefox Driver instead of Google
Adding page refreshes before the tweet_at_provider() looks for the textbox
Clicking the "Tweet" button to bring up the textbox to then try type in it
Using find.element_by_id but twitter changes id every pageload
When I comment out the first function call to test, it will find and type 6/10 times.
But when both functions are called the tweet_at_provider() always fails at grabbing the textbox and I get the StaleElement error.
import selenium, time, pyautogui
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException, StaleElementReferenceException
PROMISED_DOWN = 200
PROMISED_UP = 10
CHROME_DRIVER_PATH = "C:\Development\chromedriver.exe"
GECKODRIVER_PATH = "C:\\Users\\meeha\\Desktop\\geckodriver\\geckodriver.exe"
TWITTER_USERNAME = "my_username"
TWITTER_PASSWORD = "my_password"
class InternetSpeedTwitterBot():
def __init__(self, driver_path):
self.driver = webdriver.Chrome(executable_path=driver_path)
self.down = 0
self.up = 0
def get_internet_speed(self):
self.driver.get("https://www.speedtest.net/")
self.driver.maximize_window()
time.sleep(2)
go = self.driver.find_element_by_xpath("//*[#id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[1]/a/span[4]")
go.click()
time.sleep(40)
self.down = self.driver.find_element_by_xpath("//*[#id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[2]/div/div[2]/span")
self.up = self.driver.find_element_by_xpath("//*[#id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[3]/div/div[2]/span")
print(f"Download Speed: {self.down.text} Mbps")
print(f"Upload Speed: {self.up.text} Mbps")
time.sleep(3)
def tweet_at_provider(self):
self.driver.get("https://twitter.com/login")
self.driver.maximize_window()
time.sleep(3)
username = self.driver.find_element_by_name("session[username_or_email]")
password = self.driver.find_element_by_name("session[password]")
username.send_keys(TWITTER_USERNAME)
password.send_keys(TWITTER_PASSWORD)
password.submit()
time.sleep(5)
tweet_compose = self.driver.find_element_by_xpath('//*[#id="react-root"]/div/div/div[2]/header/div/div/div/div[1]/div[3]/a/div/span/div/div/span/span')
tweet_compose.click()
time.sleep(2)
textbox = self.driver.find_element_by_xpath('//*[#id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div[3]/div/div/div/div[1]/div/div/div/div/div[2]/div[1]/div/div/div/div/div/div/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div')
textbox.send_keys(f"Hey #Ask_Spectrum, why is my internet speed {self.down.text} down / {self.up.text} up when I pay for {PROMISED_DOWN} down / {PROMISED_UP} up???")
bot = InternetSpeedTwitterBot(CHROME_DRIVER_PATH)
bot.get_internet_speed()
bot.tweet_at_provider()
I had the same error there and figured out that HTML tag was instantly changing as soon as I was typing something on the twitter text-box.
tackle this problem using XPATH of span tag that was showing up after typing space from my side. break tag is the initial tag when there is not any text prompted by you, only after you type anything turns into and that's when you have to copy XPATH and use it for your application

Can't find element Selenium

I am trying to fill in the forms in the Gmail creation page. But for some reason, my driver can't find the code. I've used all the options, path, id, name, class name, but nothing works
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')
(the sleep is just temporary, to make sure it loads completely, I know it's not efficient)
here's the link to the Gmail page:
https://accounts.google.com/signup/v2/webcreateaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Dtopnav-about-n-en&flowName=GlifWebSignIn&flowEntry=SignUp
This is the error I'm getting:
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)
Thank you for your help
I found your error and I have the solution for you. Let me first determine to you the problem. When you click on the 'Create New Account' a new window is opening. BUT your bot is still undestanding that you are located in the first window (in the one that you click on the first button in order to create the account). Thus, the bot is trying to see if there is a First Name input. That's why is failing. So, the solution is that you have to change the window that you want to specify. The way you can do it is written inside the code block.
CODE
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)
So, if you will go to line 21 you will see that I have some comments in order to tell you what these lines (from 21 until 31) are doing.
Also, I inserted all the needed code for you (first name, last name, et.c). You only have to locate the creation button (last one).
Note: Try to use ids in such cases and not class names (when the ids are clear and unique) as I already did for you.

Resources