139

I am quite new to python selenium and I am trying to click on a button which has the following html structure:

<div class="b_div">

    <div class="button c_button s_button" onclick="submitForm('mTF')">
        <input class="very_small" type="button"></input>
        <div class="s_image"></div>
        <span>
           Search
        </span>
    </div>

    <div class="button c_button s_button" onclick="submitForm('rMTF')" style="margin-bottom: 30px;">
        <input class="v_small" type="button"></input>
        <span>
              Reset
        </span>
   </div>

</div>

I would like to be able to click both the Search and Reset buttons above (obviously individually).

I have tried a couple of things, for example:

driver.find_element_by_css_selector('.button .c_button .s_button').click()

or,

driver.find_element_by_name('s_image').click()

or,

driver.find_element_by_class_name('s_image').click()

but, I seem to always end up with NoSuchElementException, for example:

selenium.common.exceptions.NoSuchElementException: Message: u'Unable to locate element: {"method":"name","selector":"s_image"}' ;

I am wondering if I can somehow use the onclick attributes of the HTML to make selenium click?

Any thoughts which can point me in the right direction would be great. Thanks.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
AJW
  • 5,569
  • 10
  • 44
  • 57

9 Answers9

147

Remove space between classes in css selector:

driver.find_element_by_css_selector('.button .c_button .s_button').click()
#                                           ^         ^

=>

driver.find_element_by_css_selector('.button.c_button.s_button').click()
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 2
    I have tried what you have suggested. I get the same `NoSuchElementException` error! – AJW Jan 25 '14 at 12:46
  • 5
    @AJW, Try `print(driver.page_source)`, and check the html actually contains the element. – falsetru Jan 25 '14 at 12:53
  • 1
    Thanks. I did `print(driver.page_source)` and found that it was named different. Strange. It clicks now when I took the spaces away and renamed. On a follow up tho: as you can see even the reset button and the search button has the same `class`: how does one distinguish between the search and reset buttons while clicking in this case? – AJW Jan 25 '14 at 12:57
  • 2
    @AJW, How aobut using xpath: `driver.find_element_by_xpath('.//div[@class="button c_button s_button"][contains(., "Search")]')` – falsetru Jan 25 '14 at 13:00
  • Thanks for the tip falsetru: I will experiment with it - I get the idea. Accepted your answer! Thanks again! – AJW Jan 25 '14 at 13:04
  • Is it possible to use selenium in tty? – MLSC Oct 16 '14 at 10:47
  • 2
    @MortezaLSC, If you mean it's possible in system where there's no GUI, it's possible. Use headless browsers. For example, PhantomJS. – falsetru Oct 16 '14 at 13:50
  • Would you be so nice to have a look at the following question? http://stackoverflow.com/questions/43435984/radio-button-does-not-get-clicked-in-selenium-python – Jan Apr 17 '17 at 14:41
43

try this:

download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.

See picture: instruction

browser.find_element_by_xpath('just copy and paste the Xpath').click()

0x90
  • 39,472
  • 36
  • 165
  • 245
Carlo 1585
  • 1,455
  • 1
  • 22
  • 40
  • 5
    Thank you very much for such a awesome lifehack. It saved many hours – Hero Guy Jul 28 '17 at 14:58
  • does this not work on a mac bc both firebug and fire path aren't showing up as add ons – Bob Mar 31 '18 at 02:44
  • Some time it's not a problem of OS but Firefox version, last Firefox version has some problem with FirePath, I'm using Firefox 55.0.3 – Carlo 1585 Apr 03 '18 at 08:24
  • 3
    You can find the element on Firefox using: Tools->Web Developer->Inspector; click on the button at the GUI, on the inspector part, right click with the mouse on the relevant code-> copy and choose: CSS Selector / CSS Path / Xpath ... – Nir Jan 31 '19 at 15:43
  • Saved me hours... thanks mate.. now you don't need firebug only xPath do the whole job to find the xPath plugin here: https://addons.mozilla.org/en-US/firefox/addon/xpath_finder/ – Danhdds Apr 29 '21 at 01:43
40

For python, use the

from selenium.webdriver import ActionChains

and

ActionChains(browser).click(element).perform()
AshishGalagali
  • 526
  • 5
  • 4
9

open a website https://adviserinfo.sec.gov/compilation and click on button to download the file and even i want to close the pop up if it comes using python selenium

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

#For Mac - If you use windows change the chromedriver location
chrome_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_path)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-popup-blocking")

driver.maximize_window()
driver.get("https://adviserinfo.sec.gov/compilation")

# driver.get("https://adviserinfo.sec.gov/")
# tabName = driver.find_element_by_link_text("Investment Adviser Data")
# tabName.click()

time.sleep(3)

# report1 = driver.find_element_by_xpath("//div[@class='compilation-container ng-scope layout-column flex']//div[1]//div[1]//div[1]//div[2]//button[1]")

report1 = driver.find_element_by_xpath("//button[@analytics-label='IAPD - SEC Investment Adviser Report (GZIP)']")

# print(report1)
report1.click()

time.sleep(5)

driver.close()
Rajiv Singh
  • 958
  • 1
  • 9
  • 14
6

I had the same problem using Phantomjs as browser, so I solved in the following way:

driver.find_element_by_css_selector('div.button.c_button.s_button').click()

Essentially I have added the name of the DIV tag into the quote.

CosimoCD
  • 3,570
  • 3
  • 22
  • 31
5

The following debugging process helped me solve a similar issue.

with open("output_init.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))


xpath1 = "the xpath of the link you want to click on"
destination_page_link = driver.find_element_by_xpath(xpath1)
destination_page_link.click()


with open("output_dest.txt", "w") as text_file:
    text_file.write(driver.page_source.encode('ascii','ignore'))

You should then have two textfiles with the initial page you were on ('output_init.txt') and the page you were forwarded to after clicking the button ('output_dest.txt'). If they're the same, then yup, your code did not work. If they aren't, then your code worked, but you have another issue. The issue for me seemed to be that the necessary javascript that transformed the content to produce my hook was not yet executed.

Your options as I see it:

  1. Have the driver execute the javascript and then call your find element code. Look for more detailed answers on this on stackoverflow, as I didn't follow this approach.
  2. Just find a comparable hook on the 'output_dest.txt' that will produce the same result, which is what I did.
  3. Try waiting a bit before clicking anything:

xpath2 = "your xpath that you are going to click on"

WebDriverWait(driver, timeout=5).until(lambda x: x.find_element_by_xpath(xpath2))

The xpath approach isn't necessarily better, I just prefer it, you can also use your selector approach.

Tanel
  • 1,080
  • 9
  • 16
3

I had the same problem and with Firefox, I got button element with the following steps:

  • right click button of interest and select "Inspect Accessibility Properties"
  • this opens the inspector. Right click the highlighted line and click "Print to JSON"
  • this opens a new tab. Look for nodeCssSelector and copy the value

This allowed me to accept cookies of the website Yahoo by using.

url = "https://yahoo.com"
driver = Firefox(executable_path="geckodriver.exe")
driver.get(url)
driver.find_element_by_css_selector("button.btn:nth-child(5)").click()

I tested this further and it allowed me to accept individual cookies with ease. Simply repeat the mentioned steps from before to get the button names.

url = "https://yahoo.com"
driver = Firefox(executable_path="geckodriver.exe")
driver.get(url)
driver.find_element_by_css_selector("a.btn").click()
driver.find_element_by_css_selector(".firstPartyAds > div:nth-child(2) > label:nth-child(1)").click()
driver.find_element_by_css_selector(".preciseGeolocation > div:nth-child(2) > label:nth-child(1)").click()
driver.find_element_by_css_selector("button.btn").click()

Another method is to

  • right click button of interest and select "Inspect"
  • right click the highlighted line and click "Copy -> CSS Selector" or whatever you need (there are multiple options, including XPath)

However, I think the second method may include whitespaces depending on what you copy, so you might need to manually remove (some of) them. The first method seems to be more foolproof, but I don't know if/how it works on other browsers than Firefox. The second method should work for all browsers.

Tobias
  • 31
  • 3
2

e = driver.find_element(By.XPATH, 's_image').click()

sometime it does not work! you can try:

e = driver.find_element(By.XPATH, 's_image') driver.execute_script("arguments[0].click();", e)

lam vu Nguyen
  • 433
  • 4
  • 9
1

Use This code To Click On Button

# finding the button using ID
button = driver.find_element_by_id(ID)

# clicking on the button
button.click()