Python Selenium How to handle chrome store alert? - python

I'm trying to install chrome extention with selenium but when I clicked on "Add Extension", there was an alert like the picture below showed up, I'm not sure if it is an alert or not , but I saw error "no such alert". please help me
this is how I tried to handle this
alert = driver.switch_to.alert
alert.accept()
P/s : I also tried some other ways of handling alert but it wasn't worked so I don't think it is an alert. And I also don't want to use add_extension option

EDITED
Well, if you want to click on the alert message, try using this
WebDriverWait(driver, wait_time).until(EC.alert_is_present())
alert_msg = driver.switch_to.alert
alert_msg.accept()
For some reason I was only able to click on the alert when I used the WebDriverWait to wait until the alert is present.
Workaround
If you want to add a extension you should use the options argument.
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_extension('path/to/extension.crx')
driver = webdriver.Chrome('path/to/chromedriver.exe', options=options)
To download the CRX file use this extension: link
workaround number 2
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, wait
from time import sleep
import pyautogui
driver = webdriver.Chrome(r'.\drivers\chromedriver.exe')
driver.get('https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa')
elem = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '/html/body/div[3]/div[2]/div/div/div[2]/div[2]/div/div')))
elem.click()
sleep(3)
pyautogui.hotkey('tab','enter', interval=0.1)

Related

Selenium ElementNotInterectable

Hello there I try to scrape this website - https://dom.ria.com/uk/realtors/ and I get a popup message below about cookies when I press accept it dismiss and I can access phone numbers but When I try to press this button using selenium I get erro ElementNotInterectable.
Here is my code to handle it:
cookies = driver.find_element(By.XPATH, "//label[#class='button large']")
driver.implicitly_wait(20)
cookies.click()
I tried to use driver.implicitly_wait() but it still doesn't work.
How can I fix this?
Your xpath matches two elements on the page. In this case, selenium simply grabs the first element, which does not happen to be the one that you want. Try something like this:
cookies = driver.find_elements(By.XPATH, "//label[#class='button large']")
# wait if you have to
cookies[1].click()
A reliable way of accepting cookies on that page would be:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
### other imports, setting up selenium, etc ##
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
wait = WebDriverWait(browser, 20)
url = 'https://dom.ria.com/uk/realtors/'
browser.get(url)
try:
wait.until(EC.element_to_be_clickable((By.XPATH, '//div[#class="nowrap gdpr_settings_not_checked"]/label'))).click()
print('accepted cookies')
except Exception as e:
print('no cookie button!')
Selenium docs can be found at https://www.selenium.dev/documentation/

handle popups in selenium python

I am currently working on a project where I am automating whatsapp messages through url. like this https://wa.me/number_here
whenever i do it normally everything goes fine, but when I try to automate this a whatsapp popup box appears and blocks everything, I mean everything, no right-click no developer options, that is why i cant get the x path of the button on that popup. i have tried (driver.shift_to,alert.close)but it says that there is no such alert. i have tried to find the button by contains(text) method but also did not work. here is my code.
chrome_options = Options()
chrome_options.add_argument('--user-data-dir = user-data')
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_argument('--disable-notifications')
chrome_options.add_argument('--disable-popup-blocking')
chrome_options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=chrome_options, executable_path= driver_path)
wait = WebDriverWait(driver, 60)
contact = f'https://wa.me/{number}'
driver.get(contact)
time.sleep(3)
alert = wait.until(EC.alert_is_present())
alert.accept()
please help me how to bypass this popup. thanks
I think, this link can be helpful for you:
https://stackoverflow.com/a/19019311/12000849
What I do is to set a conditional delay with WebDriverWait just before the point I expect to see the alert, then switch to it, like this:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("add_button").click()
try:
WebDriverWait(browser, 3).until(EC.alert_is_present(),
'Timed out waiting for PA creation ' +
'confirmation popup to appear.')
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")

Can't login to Target.com with Selenium

I'm working on a online purchase bot for target.com and I've run into a blocker. Upon providing correct username and password combination on the login page and clicking "login", I get the following error message on the target login page: "Sorry, something went wrong. Please try again.". This only occurs when running through browser automation. Just wondering if there's a workaround for this issue. Here is my code thus far:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
PATH="C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
btn_sign_in_nav = "//span[text()='Sign in']"
btn_sign_in_drop_down = "//div[#id='accountMenu']//div[text()='Sign in']"
input_username_login = "//input[#id='username']"
input_password_login = "//input[#id='password']"
btn_submit_login = "//button[#id='login']"
def xpath_explicit_wait(xpath_val, time_sec):
if type(time_sec) != int or type(xpath_val) != str:
print("NUMERICAL VALUES ONLY!")
driver.quit()
try:
element = WebDriverWait(driver, time_sec).until(
EC.presence_of_element_located((By.XPATH, xpath_val))
)
except NoSuchElementException:
driver.quit()
def login_user(url, username, password):
driver.get(url)
driver.implicitly_wait(3)
driver.find_element_by_xpath(btn_sign_in_nav).click()
xpath_explicit_wait(btn_sign_in_drop_down, 5)
driver.find_element_by_xpath(btn_sign_in_drop_down).click()
driver.implicitly_wait(3)
driver.find_element_by_xpath(input_username_login).send_keys(username)
driver.find_element_by_xpath(input_password_login).send_keys(password)
xpath_explicit_wait(btn_submit_login, 5)
driver.find_element_by_xpath(btn_submit_login).click()
There are detection mechanisms on sites like target that detect when you're using selenium and prevent the site from working.
More details can be found in the answer here: Can a website detect when you are using Selenium with chromedriver?
PhoenixBot implements a mechanism that changes the contents of the driver so that it's undetectable. Use this same mechanism and your problems will vanish, as mine did! :-D
https://github.com/Strip3s/PhoenixBot/blob/554441b3b6888a9be46b8aed6d364dc33da92e87/utils/selenium_utils.py#L150-L173
There is a bot Phoenixbot, I can't speak for the functionality 100% but the auto login portion definitely works and is python. https://github.com/Strip3s/PhoenixBot/blob/master/sites/target.py
I've been attempting to figure out how exactly it's accomplishing that but no success replicating successfully in my own code. Maybe take a look.... If you figure it out I'd love to know.
IF you have the ability to use Safari webdriver, then see the below code.
import time
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 selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Safari(executable_path='/usr/bin/safaridriver')
driver.get('https://www.target.com/')
action = ActionChains(driver)
driver.find_element(By.XPATH, '//*[#id="account"]').click()
WebDriverWait(driver, 30).until(ec.presence_of_element_located((By.XPATH, '//*[#id="accountNav-signIn"]')))
action.send_keys(Keys.ENTER)
action.perform()
WebDriverWait(driver, 10).until(ec.presence_of_element_located((By.XPATH, '//h2[#class="sc-hMqMXs sc-esjQYD eXTUDl"]')))
driver.find_element(By.ID, 'username').click()
driver.find_element(By.ID, 'username').send_keys('foo')
time.sleep(5)
driver.find_element(By.ID, 'password').click()
driver.find_element(By.ID, 'password').send_keys('bar')
time.sleep(5)
driver.find_element(By.XPATH, "//button[#id=\'login\']").send_keys(Keys.ENTER)
time.sleep(10)
driver.quit()
As #Decian Shanaghy mentioned, Target seems to be bot protected, but Safari webdriver still works.
The time.waits are not needed, you can remove them if you would like.
For anyone still seeking a solution to this, see this answer at Can a website detect when you are using Selenium with chromedriver?. I did a search through the chromedriver binary executable (MacOS in my case) and changed instances of $cdc_ to $abc_.
I originally suspected Target employs a JavaScript solution to hunting selenium users. I confirmed this suspicion by using selenium to open a browser at https://www.target.com without any automation. I attempted to manually login and obtained a 401 response with the well known "Sorry, something went wrong. Please try again." That didn't rule out a UI-based bot hunting solution but it pointed to a JavaScript hunter.

Having problems clicking an element using Selenium

I'm working on a program which will trade stocks for me in the future. I have run into some problems after Logging In, typing the symbols of the stock, and now I need to click in some kind of way to be able to go on and buy the stock. I'm pretty confident that i know how to make a click with selenium but this tricks me out. I will give away the full code if anyone wants to try the program themself, just change the path to the browser! The account is fake, so don't worry.
Code:
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
import time
browser = webdriver.Chrome('/Users/larskvist/downloads/chromedriver')
browser.get('https://www.forex.com/en-uk/account-login/')
username_elem = browser.find_element_by_name('Username')
username_elem.send_keys('kebababdulaziz#gmail.com')
password_elem = browser.find_element_by_name('Password')
password_elem.send_keys('KEbababdulaziz')
password_elem.send_keys(Keys.ENTER)
time.sleep(5)
search_elem = WebDriverWait(browser, 20).until(EC.element_to_be_clickable(
(By.CSS_SELECTOR, "input.market-search__search-input")))
search_elem.click()
search_elem.send_keys('FB')
time.sleep(2)
search_click_elem = WebDriverWait(browser, 20).until(
EC.element_to_be_clickable((By.XPATH, "//app-market-table[#class='search-results-element ng-
star-inserted']//div[#class='price--buy clickable-price arrows-flashing']")))
search_click_elem.click
The IMG shows what i want to click, when clicked manually a pop up buy option appears.
Thanks in advance!
Seems like webdriver click is not working.
Induce JS executor to click on .
search_click_elem = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//app-market-table[#class='search-results-element ng-star-inserted']//div[#class='price--buy clickable-price arrows-flashing']")))
browser.execute_script("arguments[0].click();", search_click_elem)
Browser snapshot:

Selenium Webdriver: how do respond on a prompt

I try to set up a test for a webpage using Selenium WebDriver and Python. Therefore I start the Docker image selenium/standalone-firefox.
Within this test normally a JavaScript written prompt pops up and want to receive an entry prior I can click OK.
But how can I interact with this prompt and the OK button?
On Selenium IDE the recorder uses answer on next prompt for that. How to do this with Python-Selenium? If Python does not support an corresponding command, how do I get the needed information to do the same with the available commands?
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.firefox.options import Options
# connect to docker Selenium Server
options = Options()
driver = webdriver.Remote(
command_executor='http://localhost:4444/wd/hub',
desired_capabilities=options.to_capabilities()
)
driver.get("https://www.ecalc.ch/motorcalc.php?hacker&lang=en&weight=4500&calc=auw&motornumber=1&warea=60&elevation=300&airtemp=25&motor=hacker&type=2|a60-7xs_v4_28-pole&gear=1&propeller=apc_electric&diameter=18&pitch=10.0&blades=2&batteries=topfuel_light_4500mah_-_30/45c&s=8&esc=master_spin_160_pro&cooling=good")
print(driver.title)
driver.find_element_by_id("modalConfirmOk").click()
driver.find_element_by_name("btnCalculate").click()
driver.find_element_by_id("AddCSV").click()
????
You must handle the prompt alert. Try it with:
driver.switchTo().alert().sendKeys("Your project name");
You can handle using alert class in selenium.
#Switch the control to the Alert window
obj = driver.switch_to.alert
time.sleep(2)
#Enter text into the Alert using send_keys()
obj.send_keys('test')
refer this link selenium

Categories

Resources