Selenium 4 can't find the element - python

I'm creating rambler autoreg mail using selenium python and encountered a problem that selenium can't find the item by xpath on the page, although it is there. It's clear from the error that selenium just can't find the item (error text at the very bottom). Been looking for a solution, but they are mostly all related to another problem, please help you, thanks in advance.
HTML
...
<footer class = "styles_popupFooter__1pUND" ...>
<div class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text">
<a class="styles_link___lR7s styles_link__lCdad" ... >Registration<a>
...
<div>
...
<footer>
...
Python
# Selenium 4
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class GenerateEmail:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 30)
def main(self):
url = "https://mail.rambler.ru/?utm_source=head&utm_campaign=self_promo&utm_medium=header&utm_content=mail"
self.driver.get(url)
value = '//div[#class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text"]//a[text()="Registration"]'
self.wait.until(EC.element_to_be_clickable((By.XPATH, value)))
button = self.driver.find_element(by=By.XPATH, value=value)
button.click()
def start():
try:
s = Service(executable_path='driver/geckodriver.exe')
driver = webdriver.Firefox(service=s)
g_email = GenerateEmail(driver)
g_email.main()
except Exception as e:
print(e)
finally:
driver.close()
if __name__ == '__main__':
start()
Error
Message:
Stacktrace:
WebDriverError#chrome://remote/content/shared/webdriver/Errors.jsm:186:5
NoSuchElementError#chrome://remote/content/shared/webdriver/Errors.jsm:398:5
element.find/</<#chrome://remote/content/marionette/element.js:300:16

The element Registration you are after is inside an iframe you need switch it first in order to access the element. Use Webdriverwait() and frame_to_be_available_and_switch_to_it()
def main(self):
url = "https://mail.rambler.ru/?utm_source=head&utm_campaign=self_promo&utm_medium=header&utm_content=mail"
self.driver.get(url)
self.wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//div[#data-id-frame='embed']//iframe")))
value = '//div[#class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text"]//a[text()="Registration"]'
self.wait.until(EC.element_to_be_clickable((By.XPATH, value)))
button = self.driver.find_element(by=By.XPATH, value=value)
button.click()

Related

Python selenuim) How can I click a button in Modal?

(updated question)
Hi.
I'm trying to click a button but it doesn't work.
I guess the error cause by Modal tags. But I'm not sure.
I got "NoSuchElementException" Error before I import "webdriver.support", Now I get "TimeoutException" error. I can't find a way. Can you help me?
ERROR
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Stacktrace:
Button
<button type="button" class="btn btn-warning btn-sm" id="btnReleaseVendorInfoModal"> 반출기본정보 수정</button>
Code
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# Login
# put id
driver = webdriver.Chrome()
driver.get("https://po-management.net/release/list")
time.sleep(1)
elem = driver.find_element_by_name("username")
elem.send_keys(usernameStr)
elem.send_keys(Keys.RETURN)
time.sleep(2)
# put password
password = driver.find_element_by_xpath('//*[#id="input73"]')
try:
ActionChains(driver).send_keys(Keys.TAB).send_keys(passwordStr).perform()
password.send_keys(passwordStr)
except StaleElementReferenceException:
pass
password.send_keys(Keys.RETURN)
# redirect
time.sleep(3)
url = "https://po-management.net/release/list"
driver.get(url)
# search
time.sleep(1)
search = driver.find_element_by_id("releaseSeqArray")
search.send_keys(vrorder)
search.send_keys(Keys.RETURN)
# click1
time.sleep(1)
driver.find_element_by_link_text(vrorder).click()
# click2
time.sleep(3)
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-warning.btn-sm#btnReleaseVendorInfoModal"))).click()
You need to switch to the the frame by doing :
# after the frame is activated/displayed
modal = driver.find_element_by_id('releaseCauseInfo')
driver.switch_to_frame(modal)
# all the code that interacts with the modal can come here
NB: Don't forget to switch back to the default window after you're done with the modal by using driver.switch_to_default_content()

Python Selenium trying to click button not working

I'm trying to click in a button by using CSS Selector. I've tried by using input with value, title and onclick but not working, this is html code:
<div id="botaoMarcar"><input type="button" disabled class="botao"
value="Marcar todas" title="Marcar todas" onclick="javascript:marcarDesmarcarTodos(true);"
></div>
My code:
driver = Chrome()
url = "https://www3.bcb.gov.br/sgspub/localizarseries/localizarSeries.do?method=prepararTelaLocalizarSeries"
driver.get(url)
try:
WebDriverWait(driver, 3).until(EC.alert_is_present(),
'Timed out waiting for PA creation ' + 'confirmation popup to appear.')
alert = driver.switch_to.alert
alert.accept()
except TimeoutException:
print("No Alert")
driver.implicitly_wait(5)
driver.maximize_window()
# This part is for input table code that I want to access
id_code = driver.find_element(By.ID, 'txCodigo')
id_code.send_keys(24)
id_code.send_keys(Keys.ENTER)
# Part not working exactly
clic_code = driver.find_element(By.CSS_SELECTOR, 'input[value*="Marcar todas"]')
clic_code.click()
I just went another way and implemented the function to mark all didn't seem like the element was in an iframe.
time.sleep(5)
driver.execute_script("marcarDesmarcarTodos(true);")
Import:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":""}

I am making a bot to sign into discord and write some stuff, although when i sign in, there is a pop up message which i have to close(click the 'X' button) to go to my desired channel. But through my code, it is not closing the pop up message, it just says
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="app-mount"]/div[5]/div[2]/div/div/div/div[1]/div[2]/button"}
This is my code:
from selenium import webdriver
from selenium.webdriver.common import by
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
import time, os
class dankmemer_bot:
def __init__(self):
PATH = "C:\Program Files (x86)\chromedriver.exe"
self.driver = webdriver.Chrome(PATH)
def login(self):
driver = self.driver
driver.get('https://discord.com/channels/#me/12345678901234567')
gmail = driver.find_element_by_name('email')
gmail.send_keys('example#gmail.com')
password = driver.find_element_by_name('password')
password.send_keys(os.environ.get('password_example'))
gmail.send_keys(Keys.RETURN)
#The IMPORTANT part
def close_tab(self):
driver = self.driver
button = driver.find_element_by_xpath('/html/body/div[1]/div[5]/div[2]/div/div/div/div[1]/div[2]/button')
button.click()
try:
element = WebDriverWait(driver=10).until(
EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[5]/div[2]/div/div/div/div[1]/div[2]/button'))
)
except:
driver.quit()
def search_for_channel(self):
driver = self.driver
search_for_dankmemer = driver.find_element_by_class_name('searchBar-6Kv8R2')
search_for_dankmemer.send_keys('dank-memer')
mybot = dankmemer_bot()
mybot.login()
mybot.close_tab()
mybot.search_for_channel()
and this is the html:
<button aria-label="Close" type="button" class="closeButton-ryIVwg close-hZ94c6 button-38aScr lookBlank-3eh9lL colorBrand-3pXr91 grow-q77ONN"><div class="contents-18-Yxp"><svg class="closeIcon-150W3V" aria-hidden="false" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z"></path></svg></div></button>
To Close pop up or alert we can use this code
driver.switch_to_alert()
Then write the code to close the pop up
For example:
driver.find_element_by_xpath('xpath')

Problem with location of link in Selenium/python

I have a problem. I want to click on Zadanie 1 using Selenium here:
https://buggy-testingcup.pgs-soft.com/
I tried xpath, partial links, link text and so on, but all the time I have error
Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/div/div[2]/div[1]/a/h2"}
Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Zadanie 1"}
How can I locate this link?
<a href="/task_1">
<h2>Zadanie 1</h2>
</a>
It's weird for me, because when I run code of #0m3r it works. but when i paste it to my project i get errors.
import unittest
import time
import HtmlTestRunner
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
from ASTA.Pages.HomePage import ASTA_homepage
class test_task1(unittest.TestCase):
#classmethod
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
def test_open_task(self):
driver = self.driver
driver.get("https://asta.pgs-soft.com/")
open_app = ASTA_homepage(driver)
open_app.open_buggy_app()
time.sleep(3)
open_app.open_task1()
#classmethod
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='C:/Users/Warpath/PycharmProjects/allegro_tests/venv/ASTA'))
class ASTA_homepage():
def __init__(self, driver):
self.driver = driver
def open_buggy_app(self):
self.driver.find_element_by_partial_link_text("Buggy app").click()
def open_task1(self):
link = self.driver.find_element_by_link_text("Zadanie 1")
link.click()
Find it by link text
Example
import time
from selenium import webdriver
chrome_browser = webdriver.Chrome()
url = "https://buggy-testingcup.pgs-soft.com/"
chrome_browser.get(url)
time.sleep(3)
link = chrome_browser.find_element_by_link_text("Zadanie 1")
link.click()
Try using a Selenium method other than find_element_by_xpath. You can find elements of an xpath, jspath, inner HTML, etc
find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
These are the available methods Selenium allows.
I have a form filling application where every element can be found by name but one of them needs to be found exclusively by xpath for some reason.
I was able to click on that button using this below. Also, it's always good practice to use waits when attempting to find or interact with elements.
from selenium import webdriver
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
# You will need to use the path for your driver
driver = webdriver.Chrome('/Users/Shared/Drivers/chromedriver')
driver.get('https://buggy-testingcup.pgs-soft.com/')
button = wait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '[href=\"\/task_1\"]')))
button.click()
You can find more information regarding the use of waits here: https://selenium-python.readthedocs.io/waits.html

Selecting checkboxes using selenium web driver with python

I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome and path checker on Firefox...
Here is my code and my tries are commented.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[#name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[#name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
HTML
<span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{"attribute":"whitelist_categories","value":"283155","rangeEnd":"","rangeStart":"","filterType":"checkboxes"}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
I have solved my problem with a very simple line of code using the right xpath:
self.browser.find_element_by_xpath("(//input[#name=''])[8]").click()
and it perfectly worked!
I have modified your code and now it's working
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
sleep(5)
self.browser.find_element_by_xpath("//span[#class='a-label a-checkbox-label' and contains(text(),'Books')]/preceding-sibling::input[1]").click()
self.browser.close()
if __name__ == "__main__":
unittest.main(verbosity=2)

Categories