Python - Selenium XPATH query mismatch - python-3.x

I've tested an XPATH query using Chrome SelAssist extension and it works pretty fine.
The syntax is "//*[#id="fbPhotoSnowliftTimestamp"]/a/abbr":
I've started to write a python code to detect such element:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
chrome_profile = r"C:\Users\XXX\AppData\Local\Google\Chrome\User Data"
options = webdriver.ChromeOptions()
options.add_argument('user-data-dir=' + chrome_profile)
w = webdriver.Chrome(executable_path="C:\\Projects\\selenium\\chromedriver.exe", chrome_options=options)
w.get('https://website.com')
test = w.find_element(By.XPATH, "//*[#id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")
Page is loaded fine, and it's exactly the same one I've manually tested.
Unfortunately I continue to retrieve this error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="fbPhotoSnowliftTimestamp"]/a/abbr"}
(Session info: chrome=80.0.3987.149)
I cannot figure out what I'm doing wrong.
Thx for any suggestion.

The page might not be loading as quickly as expected. A timeout exception will be thrown if the xpath is not found using below. Try:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_profile = r"C:\Users\XXX\AppData\Local\Google\Chrome\User Data"
options = webdriver.ChromeOptions()
options.add_argument('user-data-dir=' + chrome_profile)
w = webdriver.Chrome(executable_path="C:\\Projects\\selenium\\chromedriver.exe", chrome_options=options)
w.get('https://website.com')
test = WebDriverWait(w, 10).until(EC.visibility_of_element_located((By.XPATH, "//*[#id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")))
#w.find_element(By.XPATH, "//*[#id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")

Related

Selenium not checking box

Trying to get selenium to check a box with python but it seems to keep timing out.
Current code is
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://grabagun.com/giveaway')
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="terms_and_conditions"]'))).click()
The error is:
InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //*[#id="terms_and_conditions" because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[#id="terms_and_conditions"' is not a valid XPath expression.
Any suggestions?
You could use action chains and the correct lookup:
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element(By.ID, "terms_and_conditions")
ActionChains(driver).move_to_element(element).click().perform()

Scroll to right in Tradingview chart using python

I am trying to scroll right using selenium python in TradingView
My Code:
driver.find_element_by_xpath("//div[#class='control-bar__btn control-bar__btn--move-right apply-common-tooltip']").click()
It throws an error:
selenium.common.exceptions.ElementNotInteractableException: Message:
element not interactable
Try the below code -
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 60)
action = ActionChains(driver)
driver.maximize_window()
driver.get('https://www.tradingview.com/chart/')
try:
wait.until(EC.visibility_of_element_located((By.XPATH, "//span[contains(#class,\"closeIcon\")]"))).click()
except:
pass
RightScroll = wait.until(EC.presence_of_element_located((By.XPATH,"//div[contains(#class,\"btn--move-right\")]")))
for i in range(10):
time.sleep(2)
print(i)
action.move_to_element(RightScroll).click().perform()
If it solves your problem then please mark it as answer. Do let me know if you have any query.
There is a message window displayed when you first load the page. You have to close it first (to get the right arrow container visible) if you are not doing it by
driver.findElement(By.xpath(".//span[contains(#class,'closeIcon')]")).click();
driver.findElement(By.xpath(".//td[#class='chart-markup-table time-axis']")).click();//To get the right arrow container visible
driver.findElement(By.xpath(".//div[#class='control-bar__btn control-bar__btn--move-right apply-common-tooltip']")).click();

How to hit the Next button from Python using Selenium?

I am trying to work with the following site using Python.
Please advise how can I hit the Next button:
I have tried the following:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome(executable_path = r'C:/chromedriver.exe')
driver.maximize_window()
wait = WebDriverWait(driver,40)
driver.get('https://www.okcupid.com/login')
driver.execute_script('arguments[0].click();',wait.until(EC.element_to_be_clickable((By.ID, 'username'))))
wait.until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys("abc")
driver.execute_script('arguments[0].click();',wait.until(EC.element_to_be_clickable((By.ID, 'username'))))
wait.until(EC.element_to_be_clickable((By.ID, 'password'))).send_keys("123")
# Find login button
login_button = driver.find_element_by_name('Next')
# Click login
login_button.click()
But got an error:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="Next"]"}
Name is a an attribute on a webelement. The next button has no Name attribute.
You can try this xpath:
//input[#value='Next']
login_button = driver.find_element_by_xpath('//input[#value="Next"]')

Unable to click on link using python and selenium

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# go to website
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=chrome_options)
action = webdriver.ActionChains(driver)
driver.get('https://www.clinicalkey.com/#!/browse/book/3-s2.0-C2016100010X')
# look for "login" and click
loginclick = driver.find_element_by_xpath("//*[#id='header']/div[3]/ol/li[3]/a/span").click()
How come I'm not able to click on the login section on top right after navigating to the website given? I get an error:
Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='header']/div[3]/ol/li[3]/a/span"}
(Session info: chrome=85.0.4183.83)
File "C:\python\download.py", line 18, in <module>
loginclick = driver.find_element_by_xpath("//*[#id='header']/div[3]/ol/li[3]/a/span").click()
Thank you !
Two reason:
1: Wait for element to load
2: As element is not visible on page use java script to click
driver.get('https://www.clinicalkey.com/#!/browse/book/3-s2.0-C2016100010X')
# look for "login" and click
loginclick=WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, "//*[#id='header']/div[3]/ol/li[3]/a/span")))
driver.execute_script("arguments[0].click();", loginclick)
Output:

PhantomJS python issue

My python selenium tests are working on firefox dirver (GUI) without any issue. But i wanted to run my tests in headless mode. When i try to run the same script with headless mode (with few modifications). it gives wierd errors.
Ex:
selenium.common.exceptions.NoSuchElementException: Message{"errorMessage":"Unable to find element with id 'ext-gen1499
python script :
import os
import time
from selenium.webdriver.common.proxy import *
from selenium.webdriver.common.by import By
phantomjs_path=r"/home/xxxx/nodejs-installs/phantomjs-2.1.1-linux-x86_64/bin/phantomjs"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
service_args = ['--proxy=x.x.x.x:80','--proxy-type=https']
driver = webdriver.PhantomJS(executable_path=r'/home/xxxx/nodejs-installs/phantomjs-2.1.1-linux-x86_64/bin/phantomjs',service_args=service_args)
os.environ['MOZ_HEADLESS'] = '1'
driver.get("https://aaaaa.com")
def Login():
try:
driver.find_element_by_id("username").send_keys("test#aaaa.com")
driver.find_element_by_id("password").send_keys("xxxxxxx")
driver.find_element_by_id("Submit").click()
login_flag=1
except:
print("Error Loading Login page")
login_flag=0
finally:
return login_flag
def CreateMail():
try:
element = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, "button-1143-btnInnerEl")))
driver.find_element_by_id("button-1143-btnInnerEl").click()
except TimeoutException:
print ("Loading took too much time - Create New Mail")
driver.find_element_by_id("ext-gen1499").send_keys("test#test.com")
driver.find_element_by_id("textfield-1265-inputEl").send_keys("Automated Test Mail from Selenium")
driver.find_element_by_id("button-1252-btnIconEl").click()
Am i missing anything ?
It is a good practice to add an implicit wait of at-least 10 seconds , for allowing the target page element/s to load completely.
driver.implicitly_wait(10)

Resources