该报错是因为在上传图片时,WebDriverWait 没有找到上传按钮,导致 EC.presence_of_element_located 报错。需要检查 XPath 是否正确,或者增加一些等待时间来确保上传按钮已经加载完成。

Traceback (most recent call last):
  File "00.py", line 33, in <module>
    EC.presence_of_element_located((By.XPATH, '//input[@type='file']'))


import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

cookie_str = '_gid=GA1.2.521438284.1685852601; login=srtzimu; xfss=qysa23rf7bfqme45; _ga=GA1.1.607076236.1685852601; overlay=true; bcs_cookie_live_stream=1; overlay_count=14; index_ut=html5; _ga_RCR9PNF6FL=GS1.1.1685955589.9.1.1685958086.0.0.0'
upload_folder = "/home/115/up"

# set options for headless Chrome
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# add cookie and login
driver = webdriver.Chrome(options=options)
driver.get("https://imagetwist.com/")
cookies = {}
for cookie in cookie_str.split(';'):
    name, value = cookie.strip().split('=', 1)
    cookies[name] = value
    driver.add_cookie({'name': name, 'value': value})

# upload images
driver.get("https://imagetwist.com/upload")
for filename in os.listdir(upload_folder):
    if filename.endswith(".jpg") or filename.endswith(".png"):
        filepath = os.path.join(upload_folder, filename)
        upload_btn = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//input[@type='file']'))
        )
        upload_btn.click()
        time.sleep(1)
        upload_field = driver.find_element_by_xpath('//input[@type='file']')
        upload_field.send_keys(filepath)
        time.sleep(5)
        driver.find_element_by_id("upload").click()
        time.sleep(5)

driver.quit()
Selenium 上传图片报错:EC.presence_of_element_located 失败

原文地址: https://www.cveoy.top/t/topic/oslC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录