Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 443
rjbogz Avatar asked Jan 09 '15 21:01

rjbogz


People also ask

How do you click a button using Selenium in Python?

We can click a button with Selenium webdriver in Python using the click method. First, we have to identify the button to be clicked with the help of any locators like id, name, class, xpath, tagname or css. Then we have to apply the click method on it. A button in html code is represented by button tagname.

How do you click a button on Web scraping?

Using Element click selector you can select these items and buttons that need to be clicked. The scraper during scraping phase will click these buttons to extract all elements. Also you need to add child selectors for the Element click selector that select data within each element.


1 Answers

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

like image 75
Gabriel Avatar answered Oct 07 '22 14:10

Gabriel