Python Selenium trying to click button not working - python

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

Related

May I know why it shows unable to locate element?

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome('ChromeDriver')
driver.get("https://devbusiness.tunai.io/login")
time.sleep(2)
driver.maximize_window()
#log in credentials
username = driver.find_element(By.NAME, "loginUsername");
username.send_keys("kevin#tunai");
password = driver.find_element(By.NAME, "loginPassword");
password.send_keys("xxxxx");
login = driver.find_element(By.XPATH,"//*[#id='app']/div/div/div/div/div/div[2]/form/div[4]/button");
login.submit();
time.sleep(3)
driver.get("https://devbusiness.tunai.io/dashboard/salon_report_voucher")
time.sleep(3)
driver.find_element(By.XPATH, '//*[#id="packageTable"]/tbody[1]/tr/td[1]').click()
time.sleep(2)
driver.find_element(By.XPATH,'//*[#id="packageTable"]/tbody[1]/tr').click()
time.sleep(2)
#trigger the element before click
voucher = driver.find_element(By.XPATH, "//*[#id='packageTable']/tbody[2]/tr[1]")
driver.execute_script("arguments[0].click();", voucher)
time.sleep(2)
driver.find_element(By.XPATH, '//*[#id="packageTable"]/tbody[2]/tr[1]')
time.sleep(2)
#trigger the detail button
detail = driver.find_element(By.XPATH, "//*[#id='checkAll']")
driver.execute_script("arguments[0].click();", detail)
time.sleep(5)
driver.find_element(By.XPATH, "//*[#id='checkAll']")
time.sleep(5)
driver.find_element(By.XPATH, '//*[#id="voucherModal___BV_modal_body_"]/div/div/button[1]').click()
time.sleep(5)
I wanna click on the edit new price and enter a new price, save it and loop it. For now, I am not allow to enter the new price and proceed. I copied the Xpath and tried, but it failed so i m thinking because of the popout page. thats why it failed.
To click on Edit Price button. use webdriverwait() and wait for element to be clickable and following xpath.
Then wait for model to pop up and then enter the value.
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[#id='voucherModal___BV_modal_content_']//button[text()='Edit Price']"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[#id='voucherEditModal___BV_modal_content_']//input[#data-maska-tokens]"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[#id='voucherEditModal___BV_modal_content_']//input[#data-maska-tokens]"))).send_keys("1000")
you need to import below libraries.
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

Can you help me type postcode into the postcode form box on this URL

I am trying to do a tutorial and learn Selenium in python however i cant seem to get Selenium to enter the postcode into the psotcode field/form box.=
I am using:
Python v3.9
Chrome v87
This is the URL i am practicing on:
https://www.currys.co.uk/app/checkout
And this is my current code:
# Selenium Tutorial #1
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
# Open Chromedriver
driver = webdriver.Chrome(r"C:\Users\Ste1337\Desktop\chromedriver\chromedriver.exe")
# Open webpage
driver.get("https://www.currys.co.uk/gbuk/tv-and-home-entertainment/televisions/televisions/samsung-ue75tu7020kxxu-75-smart-4k-ultra-hd-hdr-led-tv-10213562-pdt.html")
# Click "Accept All Cookies" or ignore if no pop up
try:
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler")))
element.click()
except Exception:
pass
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Add to Basket" or refresh page if out of stock
try:
element = WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, "email-desktop")))
time.sleep(5)
browser.refresh()
except:
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.GZkwS")
driver.execute_script("arguments[0].click();", button)
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Continue to Basket"
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.sc-fzpjYC.gJohPa")
driver.execute_script("arguments[0].click();", button)
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Go to checkout"
button = driver.find_element_by_xpath("//button[contains(#data-component, 'Button')][contains(#type, 'button')]")
driver.execute_script("arguments[0].click();", button)
# Type in postcode
search=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//input[#contains='Postcode Checker")))
search.send_keys("NG229NU")
search.send_keys(Keys.RETURN)
your locator is wrong for search , use:
search = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//input[#aria-label="Postcode Checker"]')))

How to find hidden class with Selenium

I am currently working on a demo Selenium project with Python. I have been able to navigate to a page but when trying to collect text within a "div class" selenium fails to find the HTML :
Code to be collected
I have made use of the wait functionality but the code still does not find the Html element.
Any suggestions on how to resolve this issue would be appreciated, please see my code below :
Image of my selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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
import time
import json
# establish Json dict
global data
data = {}
global date
date = '''&checkin=2021-02-22&checkout=2021-02-28&adults=1&source'''
def find_info(place):
data[place] = []
driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://www.airbnb.co.uk/")
time.sleep(2)
#first_page_search_bar
search_bar = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "_1xq16jy")))
time.sleep(2)
search_bar.clear()
time.sleep(2)
search_bar.send_keys(f"{place}")
time.sleep(2)
enter_button = driver.find_element_by_class_name("_1mzhry13")
enter_button.click()
#load page
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "_ljad0a")))
page = driver.current_url
new_url = page.replace("&source", date)
# driver = webdriver.Chrome('chromedriver.exe')
driver.get(new_url)
time.sleep(3)
click_button = driver.find_element_by_xpath('//*[#id="menuItemButton-price_range"]/button')
click_button.click()
time.sleep(5)
price = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '/html/body/div[16]/section/div/div/div[2]/div/section/div[2]/div/div/div[1]')))
print(price)
find_info("London, United Kingdom")
I've fixed the xpath at the end of your script:
price = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '(//div[#role="menu"]//div[#dir="ltr"])[1]/preceding-sibling::div')))
print(price.text)
Explanation: Under the <div role="menu" ... there are 3 <div dir="ltr">elements and the first one happens to be just after the div you are looking for. So we find that one and select the preceding sibling.
Another recommendation: if you replace EC.presence_of_element_located to EC.element_to_be_clickable when you are looking for the input fields at the start you can get rid of a few time.sleep statements.

Can't exhaust the load more button to unveil all the headlines

I've tried to keep clicking on more button located at the bottom of a webpage (in it's landing page) to unveil all the headlines. The thing is when I execute my script, It only click once and then stop. How can I keep clicking on that button until there is no more option to click?
Link to that website
This is my script so far:
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
link = "https://www.newsnow.co.uk/h/Sport/Football/Championship/Transfer+News"
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get(link)
while True:
try:
loadmore = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[class^='hl_more']")))
driver.execute_script("arguments[0].scrollIntoView();",loadmore)
loadmore.click()
except Exception: break
driver.quit()
Try below code to simulate required behavior:
header = driver.find_element_by_id("phead")
driver.execute_script('arguments[0].style.position = "absolute";', header)
while True:
try:
loadmore = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.hl_more.bg_tween:not(.nfloading)")))
driver.execute_script("arguments[0].scrollIntoView();",loadmore)
loadmore.click()
except: break

Selenium load time errors - looking for possible workaround

I am trying to data scrape from a certain website. I am using Selenium so that I can log myself in, and then start parsing through data.
I have 3 main errors:
Last page # not loading properly. here I am loading "1" when it should be "197" and I believe this is happening because of the load associated with the website
element 'test' xpath not being found properly. I commented out in last for loop.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[1]/div[#class='col-lg-3 col-sm-3 result-info' and 2]/span[#class='brand-name' and 1]"}
finally, I am trying to click last page to test if that works, but I am getting an error that Element is not found.
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
This is my code
import selenium
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
url = "https://marketplace.refersion.com/"
username = "jupoxar#b2bx.net"
password = "testpass123"
driver = webdriver.Chrome("/Users/xxx/Downloads/chromedriver")
if __name__ == "__main__":
driver.get(url)
driver.find_element_by_xpath("/html/body/div[#class='wrapper']/div[#class='top-block']/header[#class='header clearfix']/div[#class='login-button']/a[#class='login-link']").click()
driver.find_element_by_id("email").send_keys(username) # enters the username in textbox
driver.find_element_by_xpath("/html/body/div[#id='app']/div[#class='top-block']/div[#class='row']/div[#class='col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 main-section']/div[#class='main-section-content']/div/form[#class='form-horizontal']/div[#class='form-group ']/div[#class='col-xs-12 col-sm-10 col-sm-offset-1 input-group input-group-lg']/input[#id='password']").send_keys(password) # enters the password in textbox
# Find the submit button using class name and click on it.
driver.find_element_by_class_name("btn-primary").click()
driver.find_element_by_link_text("Find Offers").click()
driver.find_element_by_id("sorting-dropdown").click() # enters the username in textbox
driver.find_element_by_link_text("Newest First").click()
last_page = driver.find_element_by_class_name("right-center").text
print(last_page)
# try:
# last_page = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.CLASS_NAME, 'right-center')))
# print("Page is ready!")
# except TimeoutException:
# print("Loading took too much time!")
for i in range(1, 10):
# test = driver.find_element_by_xpath("//div[1]/div[#class='col-lg-3 col-sm-3 result-info' and 2]/span[#class='brand-name' and 1]")
# print(test)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'hover-link'))).click()
I think this has to do with the way the page is being loaded. My question is, is there any work around to something like this?
You should have explicit waits in your code to handle the dynamic loading of the pages. Sorting the page by "Newest First" causes it to refresh the results and introduces a spinner to indicate the sorting.
<i class="fa fa-spinner fa-spin" aria-hidden="true" style="font-size: 48px;"></i>
Waiting for the spinner to disappear should give you the correct page count. Something on the following lines:
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
.....
# your login code
.....
driver.find_element_by_link_text("Newest First").click()
element = WebDriverWait(driver, 10).until(
EC.invisibility_of_element_located((By.XPATH, "//i[#class='fa fa-spinner fa-spin']"))
)
last_page = driver.find_element_by_class_name("right-center").text
To find all the brand names listed on the page, you need to find all the span tags with class='brand-name' by calling the method find_elements_by_xpath(plural, elements)
brand_names_list = driver.find_elements_by_xpath("//span[#class='brand-name']")
for brand_name in brand_name_list:
print brand_name.text

Categories