I am trying to do a tutorial and learn Selenium in python however i cant seem to get Selenium to click the "Add To Cart" button using either find_element_by_class or find_element_by_XPATH. The problem is to check if the item is out of stock, and if it is out of stock then to refresh the webpage and restart the script. If the item is in stock then it should click "Add To Cart"
I am using:
Python v3.9
Chrome v87
This is the URL i am practicing on:
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
And this is my current code for the clicking:
# 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
driver = webdriver.Chrome(r"C:\Users\Ste1337\Desktop\chromedriver\chromedriver.exe")
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")
#search = driver.find_element_by_id(ContentPlaceHolder1_NotifyBtn)
link = driver.find_element_by_id("onetrust-accept-btn-handler")
link.click
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler"))
)
element.click()
except Exception:
pass
driver.implicitly_wait(2)
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, "email-desktop"))
)
time.sleep(1)
browser.refresh()
except:
driver.find_element_by_class_name("Button__StyledButton-bvTPUF hZIOeU Button-jyKNMA GZkwS")
link.click()
You cannot pass multiple classes to find_element_by_class_name. Instead use driver.find_element_by_css_selector or xpath.
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(r"C:\Users\Frank\Documents\Python Scripts\chromedriver_win32\chromedriver.exe")
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")
#search = driver.find_element_by_id(ContentPlaceHolder1_NotifyBtn)
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler"))
)
element.click()
except Exception:
pass
driver.implicitly_wait(2)
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, "email-desktop"))
)
time.sleep(5)
driver.refresh()
except:
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.GZkwS")
Next, if you would call button.is_displayed() it will return False, because it is a hidden element. This means you cannot interact with it using button.click(). Instead, you can use javascript to click the button.
driver.execute_script("arguments[0].click();", button)
Related
This is my first time using Python and Selenium. The first part of the code works but when it goes to the second page it can never find any of the elements. If I flip the code and make it go to the second site first, it works. What am I doing wrong here? I tried xpath, CSS_Selector, Class_Name seems like nothing is working. This is the error I get:
Traceback (most recent call last):
File "C:\Users\dresd\PycharmProjects\Test2\main.py", line 20, in
click_Register = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap"))).click()
File "C:\Users\dresd\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 89, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome ("C:/chromedriver.exe")
driver.get("https://10minutesemail.net/")
Copy_Email = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.ID, "copyEmailAddress"))).click()
time.sleep(10)
driver.execute_script("window.open('https://quora.com/','_blank')")
click_Register = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap"))).click()
name = driver.find_element(By.NAME, "profile-name")
email = driver.find_element(By.ID, "email")
name.send_keys("Jackson Fuller")
Thanks in advance!
You have to switch the driver to the new opened tab.
Without that the focus will remain on the first browser window.
TimeoutException actually means that Selenium could not locate element by passed locator.
Also the locator you are using is bad.
Try this:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome ("C:/chromedriver.exe")
driver.get("https://10minutesemail.net/")
Copy_Email = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.ID, "copyEmailAddress"))).click()
time.sleep(10)
driver.execute_script("window.open('https://quora.com/','_blank')")
driver.switch_to.window(driver.window_handles[1])
click_Register = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CLASS_NAME, "q-text qu-ellipsis qu-whiteSpace--nowrap"))).click()
name = driver.find_element(By.NAME, "profile-name")
email = driver.find_element(By.ID, "email")
name.send_keys("Jackson Fuller")
This is my code and it works completely fine for selecting size but it does not click the add to cart button as I can not see the product being added to my cart.
from selenium import webdriver as wd
import chromedriver_binary
from selenium.webdriver.common.action_chains import ActionChains
wd= wd.Chrome()
action= ActionChains(wd)
wd.implicitly_wait(1)
url="https://www.nike.com/ca/launch/t/air-max-pre-day-pure-platinum"
wd.get(url)
#wd.maximize_window()
size=wd.find_element_by_xpath('//*[#id="root"]/div/div/div[1]/div/div[1]/div[2]/div/section[1]/div[2]/aside/div/div[2]/div/div[2]/ul/li[15]/button')
size.click()
wd.implicitly_wait(1)
cart=wd.find_element_by_xpath('//*[#id="root"]/div/div/div[1]/div/div[1]/div[2]/div/section[1]/div[2]/aside/div/div[2]/div/div[2]/div/button')
action.move_to_element(cart)
action.click()
action.perform()
do not comment this :
#wd.maximize_window()
you are using absolute xpaths, which seems to be locating the right element, I would suggest you to write relative xpath and with Expected conditions :
and you need to scroll also :
driver.execute_script("window.scrollTo(0, 250)")
and then do this :
size=wd.find_element_by_xpath('//*[#id="root"]/div/div/div[1]/div/div[1]/div[2]/div/section[1]/div[2]/aside/div/div[2]/div/div[2]/ul/li[15]/button')
size.click()
Update 1 :
driver = webdriver.Chrome()
driver.maximize_window()
wait = WebDriverWait(driver, 10)
driver.implicitly_wait(10)
driver.get("https://www.nike.com/ca/launch/t/air-max-pre-day-pure-platinum")
sleep(10)
driver.execute_script("window.scrollTo(0, 750)")
action = ActionChains(driver)
action.move_to_element(wait.until(EC.visibility_of_element_located((By.XPATH, "//figure[contains(#data-qa,'card-product-image-3')]")))).perform()
action.move_to_element(wait.until(EC.visibility_of_element_located((By.XPATH, "//figure[contains(#data-qa,'card-product-image-5')]")))).perform()
action.move_to_element(wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='US 10.5']")))).click().perform()
action.move_to_element(wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='add to bag']")))).click().perform()
Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
See if this works:-
cart = driver.find_element_by_xpath(".//button[text()='add to bag']")
driver.execute_script("arguments[0].scrollIntoView(true);", cart)
cart.click()
Could you please help me with one issue? I have got a problem with Selenium and popup windows with agreements on youtube.
When first window is jumped - Selenium close this window, but if I want to close second window/frame, selenium doesn't work. Could you please help?
The part of code attached below:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep
class YoutubeSearcher:
def __init__(self, search):
self.search = search
def open_url(self) -> None:
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/')
try:
WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '/html/body/ytd-app/ytd-popup-container/paper-dialog/yt-upsell-dialog-renderer/div/div[3]/div[1]/yt-button-renderer/a/paper-button/yt-formatted-string'))).click()
except:
print("no alert to accept")
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="yDmH0d"]/c-wiz/div[2]/div/div/div/div/div[2]/form'))).click()
search = driver.find_element_by_id("search")
search.clear()
search.send_keys(self.search)
submit_button = driver.find_element_by_id("search-icon-legacy")
submit_button.click()
From the code you have share these are my observations :
First popup.
WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '/html/body/ytd-app/ytd-popup-container/paper-dialog/yt-upsell-dialog-renderer/div/div[3]/div[1]/yt-button-renderer/a/paper-button/yt-formatted-string'))).click()
Second popup.
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="yDmH0d"]/c-wiz/div[2]/div/div/div/div/div[2]/form'))).click()
Suggestion :
Check the xpath once if they are correct or are there multiple locators which are being returned.
Add apprropriate waits : like isVisible,clickable for both the locator popup.
Using basic if else you can make the conditions work (no specific need of try except).
After one popup is closed check if the next popup is visible or not.
This is the code that finally works. A switching frame is needed for the second pop up. It's lame, I know but it works.
Hope it helps. Good luck.
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep
driver = webdriver.Chrome('C:\Webdrivers\chromedriver.exe')
driver.maximize_window()
driver.get('https://www.youtube.com')
WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH,
'/html/body/ytd-app/ytd-popup-container/paper-dialog/yt-upsell-dialog-renderer/div/div[3]/div[1]/yt-button-renderer/a/paper-button/yt-formatted-string'))).click()
driver.switch_to.frame(0)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"/html/body/div/c-wiz/div[2]/div/div/div/div/div[2]/form/div/span/span"))).click()
I'm working to automate web page where i'm unable to close the pop up. I have tried to refresh/switch to pop up window, nothing worked.
Code:
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path='F:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.libertymutual.com/get-a-quote')
driver.maximize_window()
driver.find_element_by_xpath(
'//*[#id="1555468516747"]/section/div[2]/section/form/div[1]/div[3]/div/div[1]').click()
time.sleep(1)
driver.find_element_by_xpath('//*[#id="zipcode-1555468516747-1555468516747"]').click()
driver.find_element_by_xpath('//*[#id="zipcode-1555468516747-1555468516747"]').send_keys('03878')
time.sleep(1)
driver.find_element_by_xpath(
'//*[#id="1555468516747"]/section/div[2]/section/form/div[2]/div[5]/div/div/button').submit()
time.sleep(5)
x=driver.find_element_by_xpath('//*[#id="discount-marketing-modal"]/header/button/svg').click()
driver.refresh()
If you want directly go to web page, https://buy.libertymutual.com/auto?city=Somersworth&jurisdiction=NH&lob=Auto&policyType=Auto&zipCode=03878
Replace last 3 lines of your code by below lines.Used action chain to click.
time.sleep(5)
ok = driver.find_element_by_xpath('//*[#id="discount-marketing-modal"]/footer/button')
ActionChains(driver).move_to_element(ok).pause(1).click(ok).perform()
x=driver.find_element_by_xpath('//*[#id="discount-marketing-modal"]/header/button/svg').click()
This is css selector for popup close button : .lm-Icon.lm-Icon-Close
But this element can't use the .click() method, the .click() method will produce this error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted:
Use ActionChains to solve this problem.
You can try the following code:
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 import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(executable_path='F:\chromedriver_win32\chromedriver.exe')
driver.get('https://www.libertymutual.com/get-a-quote')
driver.maximize_window()
wait = WebDriverWait(driver, 20)
auto_element = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[#class='quotingText']//span[contains(text(), 'Auto')]")))
auto_element.click()
zip_code = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.zipcode")))
zip_code.click()
zip_code.send_keys("03878")
driver.find_element_by_css_selector('div.buttonWrapper button').submit()
popup_close_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".lm-Icon.lm-Icon-Close")))
action = ActionChains(driver)
action.move_to_element(popup_close_btn).click(popup_close_btn).perform()
WebDriverWait better than time.sleep(..)
Here is my code so far, note that the web page loads up with a captcha. I countered this with adding a time.sleep so I can run tests. When I try to submit the form by submitting "Create new account", I get an error saying the element has no attribute for 'submit'. I tried finding the element using xpath, css_selectos, tags, class names, etc.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
browser = webdriver.Chrome()
browser.get('https://www.bstn.com/en/register/address')
time.sleep(35)
elam = browser.find_element_by_css_selector("[value='Create new account']")
elam.Submit()
If you are trying to click on Create new account button after filling information then please find below xpath to click on it
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//input[#class='button radius charcheck-submit']"))).click()
Another solution with action class
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver import ActionChains
actionChains = ActionChains(driver)
submit = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//input[#class='button radius charcheck-submit']")))
actionChains.move_to_element(submit).click().perform()
Working code
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome(executable_path=r"C:\New folder\chromedriver.exe")
# browser = webdriver.Chrome()
browser.get('https://www.bstn.com/en/register/address')
time.sleep(35)
WebDriverWait(browser, 10).until(
EC.element_to_be_clickable((By.XPATH, "//input[#class='button radius charcheck-submit']"))).click()