I'am new to mobile automation. I thought I got the gist, but I ran into a problem.
An error occurs when using the command send_keys()
selenium.common.exceptions.InvalidElementStateException: Message: Cannot set the element to '321785214'. Did you interact with the correct element?
I have a code
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_cap)
# Skip fingerprint
driver.find_element_by_xpath("//android.widget.Button[#bounds='[413,1802][668,1877]']").click()
# Click Continue
driver.find_element_by_xpath("//android.widget.Button[#content-desc='Continue']").click()
# Click to input phone number
input_phone_number = driver.find_element_by_xpath("//android.widget.EditText").click()
input_phone_number_edit = driver.find_element_by_class_name("android.widget.EditText")
# Enter phone number
input_phone_number_edit.send_keys("321785214")
And I have code from other mobile app and this code is working
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_cap)
# click to Set up later button
set_up_later_btn = driver.find_element_by_xpath('//android.widget.Button[#content-desc="Set up later"]').click()
input_phone_number = driver.find_element_by_xpath('//android.view.View[#content-desc="Phone number"]').click()
input_phone_number_edit = driver.find_element_by_class_name('android.widget.EditText')
driver.implicitly_wait(50)
input_phone_number_edit.send_keys('178546128')
driver.find_element_by_accessibility_id("Continue").click()
I don't know why first code isn't working. I need help. Thanks
Instead of using the default send_keys method, you can use the send_keys method provided by the ActionChains class
from selenium.webdriver import ActionChains
actions = ActionChains(self.driver)
actions.send_keys("321785214")
actions.perform()
Related
I've gone through a number of similar topics here but they all seem to vary in how the pop-up window is designed. I've tried a few different ways and here is the most recent. So before I enter the login info, I need to click that client login button to access the login form but I can't even get it to open, let alone entering login information.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('C:\Login Automation\chromedriver.exe')
driver.get("https://www.datamyne.com/ ")
clientlogin = driver.find_element_by_xpath("//div[#id='holder']").click()
username = driver.find_element_by_xpath("//*[#id='user']").send_keys('myusername')
password = driver.find_element_by_xpath("//*[#id='pass']").send_keys('mypassword')
the error I'm getting here is "NoSuchWindowException: Message: no such window: target window already closed from unknown error: web view not found"
the element of the first button is this:
<a style="position: relative" href="javascript:showHide('dialog-login');" class="green-btn user-login top-right-5">Client Login</a>
and then the actual login button is another javascript line:
Login
Any tips as to how to approach this would be really appreciated!
I have inspect mention website login Form based on JavaScript. You can easily execute script through selenium. I have create a basic code snippet for you.
from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://www.datamyne.com/")
##Javascript script execute using selenium
clientlogin = driver.execute_script("javascript:showHide('dialog-login');")
driver.implicitly_wait(5)
username = driver.find_element_by_xpath('//*[#id="User"]').send_keys('myusername')
password = driver.find_element_by_xpath('//*[#id="Pass"]').send_keys('mypassword')
save = driver.find_element_by_xpath('//*[#id="formLoginDM"]/div[1]/a').click()
clientlogin = driver.find_element_by_xpath("//div[#id='holder']").click()
The xpath is off. The holder isn't what you need to click.
I suspect you want:
clientlogin = driver.find_element_by_xpath("//a[text()='Client Login']").click()
Can you try this xpath once for the 'Client Login' pop-up modal
clientlogin = driver.find_element_by_xpath("//a[#class='green-btn user-login top-right-5']']").click()
I am coding a Selenium bot (with Python) that uploads a picture to instagram from a queue in a directory. For now, I have successfully logged in on Instagram and I am now trying to interact somehow with the upload button.
I have tried to click() on it, but then a window pops up where I would normally browse my computer to find the image I want to upload. I've found that I need import autoit, but I can't understand how it works and the documentation doesn't help either, so I'd rather avoid using this.
This is what I have for now:
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
class InstaBot():
# A COOKIES POP UP ALWAYS APPEARS UPON OPENING INSTAGRAM, SO INIT ALSO CLOSES IT
# TO UPLOAD ON INSTAGRAM, THE MOBILE VERSION IS NEEDED, WE TRY TO EMULATE A GALAXY S5
def __init__(self):
mobile_emulation = {"deviceName": "Galaxy S5"}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
# experimental options for mobile emulation added
self.driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options = chrome_options)
self.driver.get("https://www.instagram.com/")
# note that this accepts all cookies
cooki = self.driver.find_element_by_xpath('/html/body/div[2]/div/div/div/div[2]/button[1]')
cooki.click()
# FINDS THE USERNAME AND PASSWORD AND TYPES 2 INPUTS ACCORDINGLY
def loginfun(self):
entrar = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[#id="react-root"]/section/main/article/div/div/div/div[2]/button')))
entrar.click()
usbar = pasbar = self.driver.find_element_by_xpath('//*[#id="loginForm"]/div[1]/div[3]/div/label/input')
usbar.send_keys(input('Username: '))
# once usbar is found, the rest will be as well
pasbar = self.driver.find_element_by_xpath('//*[#id="loginForm"]/div[1]/div[4]/div/label/input')
pasbar.send_keys(input('Password: '))
logbtn = self.driver.find_element_by_xpath('//*[#id="loginForm"]/div[1]/div[6]/button')
logbtn.click()
# CLOSES PASSWORD SAVING AND NOTIFICATION MESSAGES IN CASE THEY APPEAR
def tryclose(self):
try:
nopass = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[#id="react-root"]/section/main/div/div/div/button')))
nopass.click()
except Exception:
pass
try:
nonot = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[4]/div/div/div/div[3]/button[2]')))
nonot.click()
except Exception:
pass
# bla bla bla
# Basically I emulate a mobile device and log into my account,
# then I have at the bottom center of the page the upload button that
# looks like this [+]. Here is what I try:
# SELECTS THE FIRST IMAGE FROM THE PENDING DIR. USES THE UPLOAD BUTTON VIA SEND_KEYS.
# AFTER THAT, IT MOVES SAID IMAGE TO THE 'DONE' DIR.
def upload(self):
# first pending image
pend_img = (os.listdir('C:/path to my queue dir')[0])
# finds the upload button and send_keys the image to it
upbtn = self.driver.find_element_by_xpath('//*[#id="react-root"]/section/nav[2]/div/div/form/input')
upbtn.send_keys('C:/path to image in queue'+pend_img)
# moves the image to the 'done' directory
os.rename('C:/path to image in queue dir'+pend_img , \
'C:/path to image in done dir'+pend_img)
After this process, this code is able to find the image in the 'pending' (queue) directory and move it to the 'done' directory, BUT it does not interact with instagram whatsoever. So send_keys() is not working. I am a newbie in this, but I recon that the HTML path to the button upbtn may be wrong, although I cannot find any other input path or anything.
NOTE: to clarify, no errors are shown, the problem is just that send_keys does not interact with the upload button with this code.
Anyone has a fool-proof solution or an intuitive way to upload to Instagram?
Following advice from the comments, I looked for all the input tags in the HTML of the page:
After my search, these are all the XPaths to the input tags I could find, all of them have type="file":
//*[#id="react-root"]/form/input
//*[#id="react-root"]/section/main/div[1]/form/input
//*[#id="react-root"]/section/nav[1]/div/div/form/input # this one is for stories i think
//*[#id="react-root"]/section/nav[2]/div/div/form/input # it should be this one
I have tried send_keys() to all of them, yet none seems to work.
If you don't mind, I recommend a package that might help and works so good!
Instabot is capable to upload photos/videos & stories emulating a mobile device.
Installation:
pip install instabot
Implementation:
#Call bot
from instabot import Bot
Then only need a few more steps:
bot = Bot()
bot.login(username = 'user', password = 'pass')
bot.upload_photo(image_path, caption = 'Hello world')
I recommend this option due to is clean, fast and reliable
More info, visit: https://pypi.org/project/instabot/
I am trying to log in to my amboss account using Selenium webdriver with python, but as I dont have much experience with it I dont understand what goes wrong. My credentials (email and password) are correct as I have used them to log into the website before.
Here is my code so far:
# run firefox webdriver from executable path
driver = webdriver.Firefox(firefox_options=options, capabilities=cap, executable_path = path_to_driver)
driver.get("https://www.amboss.com/us/account/login")
signinusername = config['amboss']['email']
signinpassword= config['amboss']['password']
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_xpath("//*[#id='signin_username']")
pwd.clear()
pwd.send_keys(signinpassword)
loginbutton = driver.find_element_by_xpath("/html/body/div[2]/div[1]/div/div/form/div[4]/input").click()
time.sleep(20)
# execute script to scroll down the page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
#element in log in page
newelement = driver.find_element_by_xpath("//*[#id='left']/p[1]/strong")
print(newelement.get_attribute('innerHTML'))
What I try to do here is log in to the platform and then grab an element which I see in the welcome page by xpath. Despite that selenium is unable to find this element and I get the following error:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[#id='left']/p[1]/strong
Does anyone understand why this happens? Is it because log in was not successful or could something else be wrong? Thanks in advance
UPDATE
The elements you were trying to fetch were in an iframe so you need to switch to that iframe so they be visible. The following works, try it.
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_id('signin_password')
pwd.clear()
pwd.send_keys(signinpassword)
loginbutton = driver.find_element_by_class_name('amboss-button').click()
time.sleep(2)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
time.sleep(2)
frames = driver.find_elements_by_tag_name('iframe')
driver.switch_to.frame(frames[4])
newelement = driver.find_elements_by_tag_name('p')[0].text # This prints the following 'You now have access to AMBOSS—an all-in-one pl....'
print(newelement)
I'm assuming you're trying to login to the system and trying to find something.
First of all your login attempt is not correct. You're entering password in the username field in your code.
Please do login like this:
At first, add this import to your python script:
from selenium.webdriver.common.keys import Keys
Then do login like this:
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_id("signin_password")
pwd.clear()
pwd.send_keys(signinpassword)
pwd.send_keys(Keys.ENTER)
I'm not logging in by clicking the button. Just hitting an ENTER after logging in.
I guess correcting the login attempt will help you to find your element and print contents inside this.
I've created an account in amboss to answer your question and after logging in the only iframe I found was from google tag manager with no contents in it. So I'm not really sure if your account contains some other web views.
Hope correcting the login attempt helps.
First you wrong this is line :
pwd = driver.find_element_by_xpath("//*[#id='signin_username']")
Please change with :
pwd = driver.find_element_by_id('signin_password')
Second, use conditional if for validation success or failed login :
click login here
time.sleep(20)#here recommendation use WebDriverWait
count = len(driver.find_elements_by_xpath("//*[#id='left']/p[1]/strong"))
if count > 0:
print("login success")
print(driver.find_element_by_xpath("//*[#id='left']/p[1]/strong").text)
else:
print("login failed")
Make sure this is the correct locator : //*[#id='left']/p[1]/strong
I am trying to scrape the Google News page in the following way:
from selenium import webdriver
import time
from pprint import pprint
base_url = 'https://www.google.com/'
driver = webdriver.Chrome('/home/vincent/wintergreen/chromedriver') ## change here to your location of the chromedriver
driver.implicitly_wait(30)
driver.get(base_url)
input = driver.find_element_by_id('lst-ib')
input.send_keys("brexit key dates timetable schedule briefing")
click = driver.find_element_by_name('btnK')
click.click()
news = driver.find_element_by_link_text('News')
news.click()
tools = driver.find_element_by_link_text('Tools')
tools.click()
time.sleep(1)
recent = driver.find_element_by_css_selector('div.hdtb-mn-hd[aria-label=Recent]')
recent.click()
# custom = driver.find_element_by_link_text('Custom range...')
custom = driver.find_element_by_css_selector('li#cdr_opt span')
custom.click()
from_ = driver.find_element_by_css_selector('input#cdr_min')
from_.send_keys("9/1/2018")
to_ = driver.find_element_by_css_selector('input#cdr_max')
to_.send_keys("9/2/2018")
time.sleep(1)
go_ = driver.find_element_by_css_selector('form input[type="submit"]')
print(go_)
pprint(dir(go_))
pprint(go_.__dict__)
go_.click()
This script manage to enter search terms, switch to the news tab, open the custom time period tab, fill in start and end date, but fails to click on the 'Go' button after that point.
From the print and pprint statement at the end of the script, I can deduct that it does find the 'go' button succesfully, but is somehow unable to click on it. The error displays as selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
Could anyone experienced with Selenium have a quick run at it and give me hints as why it returns such error?
Thx!
Evaluating the css using developer tools in chrome yields 4 elements.
Click here for the image
use the following css instead:
go_ = driver.find_element_by_css_selector('#cdr_frm > input.ksb.mini.cdr_go')
I am using Selenium Webdriver for the first time and am running a very simple script, but it is not working. I would like to open Firefox, go to LinkedIn, and enter my email address in the email login field. Using the code below, I'm able to get the first two operations to work, but the script is not properly identifying the email field, and so my email address is never being typed in anywhere.
browser = webdriver.Firefox() #Get local session of firefox
browser.get("http://www.linkedin.com") #Load page
elem = browser.find_element_by_name("session_key-login") #Find the login box
elem.send_keys("email#gmail.com" + Keys.RETURN) #Enter email into login box
How do I correctly identify the email login box and pass it to "elem"?
Try giving
element.send_keys("email#gmail.com");
instead of
elem.send_keys("email#gmail.com" + Keys.RETURN)
How about you just do
elem.send_keys("email#gmail.com")
UPDATE
The identifier used by you was incorrect, you can use either one of the below.
elem = browser.find_element_by_id("session_key-login")
elem = browser.find_element_by_name("session_key")