Reputation: 103
Probably a silly question, but I have spent a ridiculous amount of time trying to figure this out. I am building a scrapper bot using selenium in python, and I am just trying to click a button on a web page. The web page opens and resizes...
def initalize_browser():
driver.get("**website name**")
driver.maximize_window()
but I cannot get it to click a specific button. This is the buttons HTML code:
<button class="mx-auto green-btn btnHref" onclick="window.location ='/medical'" onkeypress="window.location='/medical'">
Medical and Hospital Costs
</button>
And this is my code:
click_button=driver.find_element(by=By.CLASS_NAME, value="mx-auto green-btn btnHref")
click_button.click()
This is the error I get for this code:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".mx-auto green-btn btnHref"}
I have tried out so many variations of this, including:
driver.find_element_by_xpath('//button[@class="mx-auto green-btn btnHref"]').click()
Where I get this error:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'
I have also checked to see if there are perhaps any other attributes with the same class name, but there is not. Any help would be super appreciated, thank you!
Upvotes: 2
Views: 12992
Reputation: 1424
The method find_element_by_xpath
is deprecated now. Use this line:
driver.find_element(By.XPATH, '//button[@class="mx-auto green-btn btnHref"]').click()
instead of:
driver.find_element_by_xpath('//button[@class="mx-auto green-btn btnHref"]').click()
And be sure you have this in imports:
from selenium.webdriver.common.by import By
The locator click_button=driver.find_element(by=By.CLASS_NAME, value="mx-auto green-btn btnHref")
doesn't work because By.CLASS_NAME
needs only one class name to find an element, but you gave it 3 class names. The html attribute class
consists of a list of elements divided by space. So, in this html code
<button class="mx-auto green-btn btnHref" onclick="window.location ='/medical'" onkeypress="window.location='/medical'">
Medical and Hospital Costs
</button>
the attribute class
has 3 class names mx-auto
, green-btn
and btnHref
You can't use all the 3 classes with By.CLASS_NAME
but you can use all of them using the By.XPATH
Upvotes: 5