我想使用库 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")
但这不起作用,它要求我重新上传网站中的文件
当然!要使用 Selenium 上传文件,您通常需要与文件输入元素而不是按钮元素进行交互。以下是如何调整代码以将文件正确上传到给定 URL:
这是修改后的代码:
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()
确保 XPath
//input[@type='file']
与网页上的实际文件输入元素匹配。如果没有,您可能需要检查网页并相应地调整 XPath。