Govind Sehrawat
Govind Sehrawat

Reputation: 11

Unable to click an element-Selenium python

I want to download an image from Instagram but I'm unable to click (using code) on the download button of this page

I tried to click using XPath and CSS selector but it doesn't work.

pyautogui.locateOnScreen('image.PNG') does not work most of the times.

elem=driver.find_element_by_xpath
elem('/html/body/div[1]/div[3]/div/div/div[1]/div/div[2]/a').click

driver.find_element_by_css_selector('body > div.page-wrapper > div:nth-child(5) > div > div > div.col-md-3 > div > div.button_div > a').click()

NoSuchElementException

If there's any better way of performing this task please do let me know.

Upvotes: 1

Views: 89

Answers (1)

CodeIt
CodeIt

Reputation: 3618

Here you go, you don't need to click any button to download img. If you have the link you can you urllib.request.urlretreive to download files.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import urllib.request

options = Options()
options.add_argument("--headless") # runs chrome in headless mode

driver = webdriver.Chrome(options=options)

driver.get('https://www.sssinstagram.com/p/B1cSJ8hlxXb/')

# To get the link via image displayed on the page use 
src = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/div[1]/div/img').get_attribute('src')
urllib.request.urlretrieve(src, src.split('/')[-1].split('?')[0]) # saves image with name 69346681_776681372728713_6952518582543886663_n.jpg obtained from the image url 

# to get the image via the href available on the page use 
href = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/div[1]/div/div[2]/a').get_attribute('href')
urllib.request.urlretrieve(href, href.split('/')[-1].split('?')[0])

driver.quit()

Upvotes: 2

Related Questions