Bot selenium, python. time.sleep(n) error - python

Is there anything better than selenium if I need to parse and click on DOM elements?
An open browser is optional (rather not needed).
Are there any better options for this?
BTW
Why does error appear after this time.sleep(n).
Error:
Traceback (most recent call last):
File "main.py", line 39, in <module>
print("Buy: " + str(elemGreen.text))
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 76, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=69.0.3497.100)
My Python code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
def loginCheck():
l = driver.find_elements_by_css_selector(".not-login")[0]
if(l.text == "Login or Join Trading"):
return True
else:
return False
driver = webdriver.Chrome(r"C:\Users\Andrew\Desktop\chromedriver.exe")
driver.get("https://abcc.com/markets/ethusdt")
if(loginCheck() == False):
print("Next step")
else:
print("Waiting for the login")
time.sleep(10)

expected_conditions.visibility_of_all_elements_located handles StaleElementReferenceException. You can use it to locate the element
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
def loginCheck():
elements = WebDriverWait(driver, 30).until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, 'not-login')))
l = elements[0]
if (l.text == "Login or Join Trading"):
return True
else:
return False

Related

Message: Unable to locate element, Selenium Python

I'm trying to get access to this page "fullcollege" with a bot I'm making for students. The problem is that I can't even select an element from it, and this error shows up. I have recently tested my code with another webpages like instagram and everything works perfectly. Anyone knows what can I do to solve this? Thanks in advance.
My code:
from time import sleep
from selenium import webdriver
browser = webdriver.Firefox()
browser.implicitly_wait(5)
browser.get('https://www.fullcollege.cl/fullcollege/')
sleep(5)
username_input = browser.find_element_by_xpath("//*[#id='textfield-3610-inputEl']")
password_input = browser.find_element_by_xpath("//*[#id='textfield-3611-inputEl']")
username_input.send_keys("username")
password_input.send_keys("password")
sleep(5)
browser.close()
The error:
Traceback (most recent call last):
File "c:\Users\marti\OneDrive\Escritorio\woo\DiscordBot\BetterCollege\tester.py", line 11, in <module>
username_input = browser.find_element_by_xpath("//*[#id='textfield-3610-inputEl']")
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\marti\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[#id='textfield-3610-inputEl']
The username and password field is inside and iframe you need to switch it first.
browser.get('https://www.fullcollege.cl/fullcollege/')
WebDriverWait(browser,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#logFrame")))
sleep(5)
username_input = browser.find_element_by_xpath("//input[#id='textfield-3610-inputEl']")
password_input = browser.find_element_by_xpath("//input[#id='textfield-3611-inputEl']")
username_input.send_keys("username")
password_input.send_keys("password")
import below libraries as well.
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

Python Selenium Handle popup alert

So I'm trying to make this program where I make it search for an anime on nyaa.si with filters and such, and i wanted to spice it up a little. Long story short, when I tap on the magnet button, it always asks me to prompt permission for qbittorrent to open the magnet link.PICTURE Here's the code, but the important section is at the end of it and the error I get is this:
Traceback (most recent call last):
File "c:/Users/Asus/Documents/Projects/python/selNyaaSi/main.py", line 49, in <module>
driver.switch_to.alert().accept();
File "c:\users\asus\appdata\local\programs\python\python38\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert
alert.text
File "c:\users\asus\appdata\local\programs\python\python38\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text
return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"]
File "c:\users\asus\appdata\local\programs\python\python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "c:\users\asus\appdata\local\programs\python\python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoAlertPresentException: Message: no such alert
(Session info: chrome=91.0.4472.124) alert
code:
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
import json
from time import sleep
from selenium.webdriver.common.alert import Alert
headless = False
path = 'C:\\chromedriver.exe'
options = webdriver.ChromeOptions()
if input('headless?: ') != '':
headless = True
options.add_argument('headless')
with open('urls.json', 'r') as f:
data = json.load(f)
driver = webdriver.Chrome(path, options=options)
url = data['urls']['nyaa']
driver.get(url)
if headless == False:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'themeToggle'))).click()
driver.find_element_by_class_name('navbar-toggle.collapsed').click()
driver.find_elements_by_class_name('form-control')[0].send_keys('Bleach')
temp = driver.find_elements_by_css_selector('select.form-control')
_filter = temp[0]
_category = temp[1]
_filter.click()
driver.find_element_by_css_selector('select.form-control[title=Filter] option[title="Trusted only"]').click()
_category.click()
driver.find_element_by_css_selector('select.form-control[title=Category] option[value="1_2"]').click()
driver.find_element_by_css_selector('button.btn.btn-primary.form-control').click()
temp = driver.find_elements_by_css_selector('tr.success td.text-center i.fa.fa-fw.fa-magnet')
temp[0].click()
driver.switch_to.alert().accept()
I dont see anything about alerts in your code, only the import. You should have something like this after the magnet.click():
driver.switch_to.alert().accept(); # or dismiss() if you dont want to accept

python with selenium automating login

I'm new to selenium
Here I want to ask about a problem code (actually not mine)
this is the code
aww = email.strip().split('|')
driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent")
time.sleep(5)
loginform = driver.find_element_by_xpath("//button[#data-provider='google']")
loginform.click()
mailform = driver.find_element_by_id('identifierId')
mailform.send_keys(aww[0])
driver.find_element_by_xpath("//div[#id='identifierNext']").click()
time.sleep(3)
passform = driver.find_element_by_css_selector("input[type='password']")
passform.send_keys(aww[1])
driver.find_element_by_id('passwordNext').click()
time.sleep(3)
driver.get("https://myaccount.google.com/lesssecureapps?pli=1")
open('LIVE.txt', 'a+').write(f"CHECKED : {aww[0]}|{aww[1]}")
time.sleep(3)
lessoff = driver.find_element_by_xpath('//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]').click()
driver.delete_all_cookies()
driver.close()
I'm using those code for automating turn on the less-secure apps from Gmail
and the error will pop up like this
quote Traceback (most recent call last):
File "C:\Users\ASUS\Downloads\ok\less.py", line 59, in
lessoff = driver.find_element_by_xpath('//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]').click()
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class="hyMrOd "]/div/div/div//div[#class="N9Ni5"]"}
(Session info: chrome=86.0.4240.183)
any help gonna be helpfull,sorry for my english before :)
You can simply target this xpath and .click to toggle the less secure apps.
lessoff = driver.find_element_by_xpath("input[type='checkbox']").click()
It looks like it couldn't find the element it's looking for so give some time to load the element. You can check with Wait().until.
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, 'YOUR_XPATH')))
when you try to click an element make sure it's there. above code will wait until the element located for the 10s if the element not located then it will throw an exception

Python Selenium - Unable to locate element

I just started learning selenium and I'm facing some issues with some code that should be quite easy to write..
I'm simply trying to enter "Paris" in the input field, but I keep getting the error: "Unable to locate element". Do I need to refer to the div tag or the input tag in order for it to work?
Here's my code at the moment.
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 as wait
from selenium.webdriver.support import expected_conditions as EC
import time
# Setup webdriver
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
# Open website maximized
driver.get("https://www.corsair.ca/")
driver.maximize_window()
print(driver.title)
# Select and enter destination
wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Votre destination']"))).click()
to_city = driver.find_element_by_class_name("form-control valid")
to_city.send_keys("Paris")
to_city.send_keys(Keys.RETURN)
Here's the error I have
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\FlightFinder\venv\SeleniumTutorial.py", line 26, in <module>
to_city = driver.find_element_by_class_name("form-control valid")
File "C:\Users\Admin\PycharmProjects\FlightFinder\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
return self.find_element(by=By.CLASS_NAME, value=name)
File "C:\Users\Admin\PycharmProjects\FlightFinder\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\Admin\PycharmProjects\FlightFinder\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Admin\PycharmProjects\FlightFinder\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".form-control valid"}
(Session info: chrome=86.0.4240.183)

python - Find email address on page with selenium

I am trying to get a list of email addresses from a website and am very close. The code I have can be seen below. I am getting the following error.
What happens is that there is a page of links which are then clicked on and in the following page there is an email address.
I am trying to print out the email address inside each of the pages after the link is clicked.
Here is an example of a page that the link clicks through to.
xTraceback (most recent call last): File "scrape.py", line 34, in
lookup(driver) File "scrape.py", line 26, in lookup
emailAdress = driver.find_element_by_xpath('//div[#id="widget-contact"]//a‌​').get_attribute('hr‌​ef')
File
"/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 293, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath) File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 752, in find_element
'value': value})['value'] File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 236, in execute
self.error_handler.check_response(response) File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py",
line 192, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException:
I am using python 2.7.13.
# -*- coding: utf-8 -*-
from lxml import html
import requests
import time
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
from selenium.common.exceptions import TimeoutException
def init_driver():
driver = webdriver.Firefox()
driver.wait = WebDriverWait(driver, 5)
return driver
def lookup(driver):
driver.get("http://www.sportbirmingham.org/directory?sport=&radius=15&postcode=B16+8QG&submit=Search")
try:
for link in driver.find_elements_by_xpath('//h2[#class="heading"]/a'):
link.click()
emailAdress = driver.find_element_by_xpath('//div[#id="widget-contact"]//a‌​').get_attribute('hr‌​ef')
print emailAdress
except TimeoutException:
print "not found"
if __name__ == "__main__":
driver = init_driver()
lookup(driver)
time.sleep(5)
driver.quit()
When I try and continue to the next page of links I get the following error
File "scrape.py", line 43, in
lookup(driver) File "scrape.py", line 26, in lookup
links.extend([link.get_attribute('href') for link in driver.find_elements_by_xpath('//h2[#class="heading"]/a')]) File
"/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py",
line 139, in get_attribute
self, name) File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 465, in execute_script
'args': converted_args})['value'] File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 236, in execute
self.error_handler.check_response(response) File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py",
line 192, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message:
The element reference is stale. Either the element is no longer
attached to the DOM or the page has been refreshed.
You just need more precise X-PATH (aslo with calling text method):
emailAdress = driver.find_element_by_xpath('//div[#class="body"]/dl/dd[2]').text
But this example works with Python3. Let me know if it works for you.
I would also recommend to use "XPath Helper" extension for Chrome.
This seem to be copy/paste issue. Sometimes when you copy code from StackOverflow answers, some hidden characters might be present. Your XPath in Python shell appears like '//div[#id="widget-contact"]//a‌​??'. You should re-write it manually to get rid of those ??...
Also note that your code will not work as you stuck on the first iteration- there is no turning back to search page.
Try to use below code instead:
from selenium.common.exceptions import NoSuchElementException
def lookup(driver):
driver.get("http://www.sportbirmingham.org/directory?sport=&radius=15&postcode=B16+8QG&submit=Search")
links = [link.get_attribute('href') for link in driver.find_elements_by_xpath('//h2[#class="heading"]/a')]
page_counter = 1
while True:
try:
page_counter += 1
driver.find_element_by_link_text(str(page_counter)).click()
links.extend([link.get_attribute('href') for link in driver.find_elements_by_xpath('//h2[#class="heading"]/a')])
except NoSuchElementException:
break
try:
for link in links:
driver.get(link)
try:
emailAdress = driver.find_element_by_xpath('//div[#id="widget-contact"]//a').text
print emailAdress
except NoSuchElementException:
print "No email specified"
except TimeoutException:
print "not found"

Categories

Resources