【问题标题】:Unable to click an element-Selenium python无法单击元素-Selenium python
【发布时间】:2019-08-22 06:02:40
【问题描述】:

我想从 Instagram 下载一张图片 但我无法点击(使用代码)this 页面的下载按钮

我尝试使用 XPath 和 CSS 选择器单击,但它不起作用。

pyautogui.locateOnScreen('image.PNG') 大部分时间都不起作用。

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

如果有更好的方法来完成这项任务,请告诉我。

【问题讨论】:

标签: python html css selenium automation


【解决方案1】:

给你,你不需要点击任何按钮来下载img。如果您有链接,您可以urllib.request.urlretreive 下载文件。

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()

【讨论】:

  • 非常感谢您的帮助,您能否解释一下为什么它无法点击
  • @GovindSehrawat 我很高兴它有帮助。
  • @GovindSehrawat 我能够单击该元素。我使用了与您相同的 xpath。不知道为什么它对你不起作用。但是对于这种情况,您不需要单击图像来获取图像。
  • 好的,你能推荐任何教程或其他东西来了解更多关于 urllib 库的信息
  • @GovindSehrawat 发生了什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
相关资源
最近更新 更多