2

I have the following Code that goes to a URL(www.example.com), and clicks on a link(Example 1). (This part works fine)

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.example.com")

link = driver.find_element_by_link_text('Example 1')
link.click()

Now, when we click on 'Example 1' link, it opens a confirmation window, with 2 buttons: 'Yes I am authorized user to this site' and 'No I am a new visitor to this site'

So, I wish to click on 'Yes I am authorized user to this site' and then finally enter my log-in credentials. I have written these 2 lines, just below the above code, for clicking on that button. But these don't work.

button = driver.find_element_by_name("'Yes I am authorized user to this site'")
button.click()
Aditya
  • 615
  • 3
  • 12
  • 26
  • Does the button have the quotation marks on it? Because based on your code you're saying the button says `'Yes I am authorized user to this site'` – Harrison Aug 24 '16 at 14:10
  • Yes, it has those quotation marks – Aditya Aug 24 '16 at 14:11
  • Is there any way you can provide the link to the website, or at the very least screenshots because I don't really see anything wrong with your code. It might have something to do with the site itself. – Harrison Aug 24 '16 at 14:13
  • I have also tried : (1) driver.find_element_by_link_text (2) driver.find_element_by_class_name . But none of these works – Aditya Aug 24 '16 at 14:15
  • Can you provide a link? – Harrison Aug 24 '16 at 14:16
  • Does the button have an XPATH? Selecting/Finding by XPATH is much simpler in Selenium. If you have Chrome, you can open the page, bring up the modal, and then _Right-Click_ > _Inspect_ and on the gray-highlighted section in the Inspection Window, _Right-Click_ > _Copy_ > _Copy XPATH_ I use XPATH for all of my selections in Selenium (see: [This SO question about XPATH Copying] (http://stackoverflow.com/questions/3030487/is-there-a-way-to-get-the-xpath-in-google-chrome)) – dblclik Aug 24 '16 at 14:18
  • @Harrison It's a simple confirmation window. Similar to one when we logout of some websites **Are you sure you want to log-out** – Aditya Aug 24 '16 at 14:21
  • By you saying "it's a simple confirmation window" you're not helping me help you whatsoever. It could be anything. If you can't provide an example of what it looks like, then I can't help you... – Harrison Aug 24 '16 at 14:26
  • @dblclik Actually I am new to Web-Scrapping. Can you please explain how to open URL in chrome and mention the XPath in python code so that it clicks on that button.. – Aditya Aug 24 '16 at 14:30
  • You don't find the XPath using Python. You find the XPath on your own using Chrome's inspect element feature and then you pass the XPath to Selenium. – Harrison Aug 24 '16 at 14:33
  • Could you share this confirmation window HTML??? – Saurabh Gaur Aug 24 '16 at 14:40
  • @Harrison I meant that I have found and copied the XPath for the button. Now how to use this XPath in our code to open URL (in Chrome) and automatically click on that button ? – Aditya Aug 24 '16 at 15:13
  • @Aditya: where have you shared the link? I do not see this anywhere. Also, if you follow either my directions above or the link to another SO question you'll be able to get the XPATH and use Selenium's built-in Find By XPATH functionality. If you provide the actual, valid URL we could help you much more easily than with a dummy URL and vague description. – dblclik Aug 24 '16 at 19:45
  • @dblclik finding by XPath is also not working. – Aditya Aug 25 '16 at 07:10
  • OK **the issue was of time**.. I used ' time.sleep(1) ' and then XPath worked fine. Thanks Everyone – Aditya Aug 25 '16 at 11:13
  • @Aditya, this seems to tell me that you're not having your driver wait for the element. I would recommend using something along this line to wait for the element to be available: `button = driver.wait.until(EC.element_to_be_clickable((By.XPATH, """//*[@id="ctl00_MainContent_welcomeText"]/div/div[3]/input""")))`. This `wait.until` approach will make sure the element has loaded before your driver tries to click it and will be more reliable than a time.sleep() – dblclik Aug 25 '16 at 12:53

3 Answers3

5

If it is an alert window, you need to use the Alert command.

#import Alert
from selenium.webdriver.common.alert import Alert
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.example.com")

link = driver.find_element_by_link_text('Example 1')
link.click()
Alert(driver).accept()
#to dismiss alert
#Alert(driver).dismiss()

I think this would have solved your query.

Jeril
  • 7,858
  • 3
  • 52
  • 69
1

Based on the comment conversation, I would recommend both using an XPATH search (instead of Name or Id) and waiting for elements to be clickable or loaded. When web-driving or web-scraping, pages may intentionally or accidentally load slowly and this can cause issues if you have pauses or waits either hard coded or non-existent. This snippet of code should allow you to search Google using Selenium and Chromedriver (you can modify the driver function to use Firefox or something else if you'd like):

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 ElementNotVisibleException
from selenium.webdriver.chrome.options import Options
from time import sleep

def init_driver(drvr_path):
    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(drvr_path+'chromedriver.exe',chrome_options=chrome_options)
    driver.wait = WebDriverWait(driver, 5)
    return driver

def lookup(query, driver=None, drvr_path=''):
    driver = None
    if driver is None:
        driver = init_driver(drvr_path)
    driver.implicitly_wait(45) # Allow up to 45 Seconds for page to load
    driver.get("http://www.google.com")
    try:
        box = driver.wait.until(EC.presence_of_element_located((By.XPATH, """//*[@id="lst-ib"]""")))
        box.send_keys(query)
        sleep(3) # Let you see the window open
        button = driver.wait.until(EC.element_to_be_clickable((By.XPATH,"""//*[@id="sblsbb"]/button""")))
        try:
            button.click()
        except ElementNotVisibleException, s:
            print "Error Handled: "+str(s)
            button = driver.wait.until(EC.element_to_be_clickable((By.XPATH,"""//*[@id="sblsbb"]/button""")))
            try:
                button.click()
            except:
                print "Could not search Google..."
                return
        resp=driver.page_source.encode('utf-8')
        with open(query+'.html','wb') as f:
            f.write(resp)
            print 'Wrote the File...'
    except:
        print("Box or Button not found in google.com")
    driver.quit()

For example, if your Chromedriver.exe file was located in your default Python path, you could do something like: lookup('Selenium Python XPATH Examples') and it should download an HTML file of the Google Search results. If you already have a Driver initialized, you could of course pass that to it.

Hope this helps

dblclik
  • 406
  • 2
  • 8
0

Try this code, hope it will help you

from selenium import webdriver
import time

driver = webdriver.Chrome('path to chromedriver\chromedriver.exe')
driver.get('https://www.example.com')
driver.maximize_window()

link = driver.find_element_by_link_text('Example 1')
link.click()
handles =driver.window_handles # this will give window handles

driver.switch_to.window(handles[1])
button = driver.find_element_by_name("'Yes I am authorized user to this site'")
button.click()
thebadguy
  • 2,092
  • 1
  • 22
  • 31