如何使用 selenium python 上传多个/单个文件?

问题描述

我被困在一个我试图将文件上传到网站的项目中。这是www.coursehero.com

其实我是在做一个脚本,在我提到的网站上自动上传文档,这是一个教育网站。

此外,网站有时可能会显示验证码,但如果您通过添加数据目录加载 cookie,那么它通常不会要求解决验证码。首次使用 selenium 浏览器可能需要通过延长时间限制手动登录

这是上传页面的直接链接https://www.coursehero.com/upload/?__chid=61cbbae8-cd73-4877-b30d-7826dfd0833e

您可以使用以下id和pwd登录

ch344g1ver+izaan100@gmail.com
izaan100

这是我的代码

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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
from selenium.common.exceptions import TimeoutException
import time
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.proxy import Proxy,ProxyType
import csv
import pandas as pd
import sys
import random
import os
#import autoit


options = Options()
#options.add_argument('--proxy-server=%s' % Ip)
options.add_argument('--user-agent={Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/90.0.4430.212 Safari/537.36}')
options.add_argument("user-data-dir=C:\\Users\\name\\AppData\\Local\\Google\\Chrome\\User Data\\selenium1")
options.add_experimental_option("excludeSwitches",["enable-automation"])
options.add_experimental_option('useAutomationExtension',False)
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--remote-debugging-port=9222")
options.add_argument('--no-sandBox')
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("disable-infobars")
path=r'C:\Users\name\Downloads\chromedriver.exe'
driver = webdriver.Chrome(path,options=options)
driver.get('https://www.coursehero.com/login/?ref=login') 
time.sleep(6)






try:
    driver.find_element_by_xpath('//*[@id="email-address-field"]').send_keys('ch344g1ver+izaan100@gmail.com')
    driver.find_element_by_xpath('//*[@id="password-field"]').send_keys('izaan100')
    driver.find_element_by_xpath('//*[@id="login-submit-field"]').click()
    time.sleep(8)
except:
    pass



driver.get('https://www.coursehero.com/upload/?__chid=61cbbae8-cd73-4877-b30d-7826dfd0833e')
time.sleep(12)

upload=driver.find_element_by_xpath('//*[@id="noFrictionUploaderApp"]/div/div/div[2]/div/div/div/div/div/div/div/div/div[2]/div/span/button/span')
upload.send_keys('C:\\Users\\name\\Desktop\\files\\Example.docx')
time.sleep(10)

我想要的是上传文件,但出现错误

Error: Element not found

代码不起作用,我尝试了其他东西,例如:

upload.send_keys(r'C:\Users\name\Desktop\files\Example.docx')

但没有用,我在谷歌和堆栈上搜索,但这是我发现在 selenium python 中上传文件的唯一方法

谁能指导我并帮助我?

解决方法

您需要找到 input 标签,然后发送密钥,将 link_to_file 放入 span 标签。

你可以试试这个 xpath //input[@type='file']

enter image description here

,

我还没有运行您的代码,但我注意到在网站上您必须实际单击按钮才能打开文件对话框,而您没有这样做。您是否尝试过在选择 xpath 后包含 .click() selenium 命令?