rjbogz
rjbogz

Reputation: 870

python clicking a button on a webpage

I currently have a script that logs me into a website and I want to have it click a button on the website if it is currently not clicked. Here is the info for the button:

When the button is already active:

<p class="toast_btn">
    <a class="button grey toast track-click active" data-user-avatar="https://dwebsite.net/picture.jpg" data-checkin-id="123456789" data-href=":feed/toast" data-track="activity_feed" href="#">

When the button is not active:

<p class="toast_btn">
    <a class="button grey toast track-click" data-user-avatar="https://dwebsite.net/picture.jpg" data-checkin-id="123456789" data-href=":feed/toast" data-track="activity_feed" href="#">

I am only looking to click it when class="button grey toast track-click"

What is the best way to do this? I currently use urllib2 and mechanize to login and check a few forms currently. Thanks!

Upvotes: 17

Views: 126331

Answers (1)

Gabriel
Gabriel

Reputation: 3604

When I compare the two tags I see that the difference is for the class tag. So if you can read it then you're done

You can do it with Selenium if you like

Step 1: find the XPath - Get the XPath of the button: for that right open the page in Chrome click on it and select Inspect element - It will open the html file and right click on the highlighted line and select copy Xpath - Copy the XPath in NotePad

Now that you have the XPath you can select the button via a Python script and query the attributes

Here is a prototype

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.youradress.org")#put here the adress of your page
elem = driver.find_elements_by_xpath("//*[@type='submit']")#put here the content you have put in Notepad, ie the XPath
button = driver.find_element_by_id('buttonID') //Or find button by ID.
print(elem.get_attribute("class"))
driver.close()

Hope that helps, if you have question please let me know

I used these links for documentation

Python Selenium: Find object attributes using xpath

https://selenium-python.readthedocs.io/locating-elements.html

Upvotes: 24

Related Questions