在Python中使用Selenium上传文件

问题描述 投票:0回答:1

我想使用库 selenium 在网站“https://www.cutout.pro/photo-enhancer-sharpener-upscaler/upload”上上传文件。你能帮我吗?

from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('window-size=2560,1440')
url = 'https://www.cutout.pro/photo-enhancer-sharpener-upscaler/upload'


driver = webdriver.Chrome(executable_path='G:/check file/python/image scraping 2/chromedriver.exe',options=options)

driver.get(url)
s = driver.find_element_by_xpath("/html/body/div/div/div/div/div[2]/div/div[1]/div/div[2]/div/button")
sleep(5)
s.send_keys("G:/check file/python/image scraping 2/1.jpg")
    

但这不起作用,它要求我重新上传网站中的文件

python python-3.x selenium-webdriver
1个回答
0
投票

当然!要使用 Selenium 上传文件,您通常需要与文件输入元素而不是按钮元素进行交互。以下是如何调整代码以将文件正确上传到给定 URL:

  1. 使用 XPath 或其他选择器查找文件输入元素。
  2. 使用send_keys方法通过指定文件路径上传文件。

这是修改后的代码:

from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('window-size=2560,1440')
url = 'https://www.cutout.pro/photo-enhancer-sharpener-upscaler/upload'

driver = webdriver.Chrome(executable_path='G:/check file/python/image scraping 2/chromedriver.exe', options=options)

driver.get(url)
sleep(5)  # Allow time for the page to load completely

# Find the file input element
file_input = driver.find_element_by_xpath("//input[@type='file']")

# Upload the file
file_input.send_keys("G:/check file/python/image scraping 2/1.jpg")

# Optionally, add more sleep to observe the result before closing the browser
sleep(10)

# Close the browser
driver.quit()

说明

  1. 选项配置:设置选项以避免记录并设置窗口大小。
  2. URL 导航:浏览器导航到提供的 URL。
  3. 文件输入元素:脚本使用 XPath 查找文件输入元素。
  4. 文件上传:脚本使用send_keys上传文件。

确保 XPath

//input[@type='file']
与网页上的实际文件输入元素匹配。如果没有,您可能需要检查网页并相应地调整 XPath。

© www.soinside.com 2019 - 2024. All rights reserved.