在 Selenium 中,文件上传可以通过以下步骤进行自动化:

  1. 找到文件上传的 input 元素。可以使用 find_element_by_xpathfind_element_by_id 或其他定位方式来定位该元素。

  2. 使用 send_keys 方法将文件路径传递给 input 元素。例如,element.send_keys('C:/path/to/file.txt')

  3. 确保文件上传的 input 元素没有设置 display: none; 属性,否则将无法定位到该元素。

以下是一个示例代码:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://example.com")

# 找到文件上传的 input 元素
upload_input = driver.find_element_by_xpath("//input[@type='file']")

# 上传文件
upload_input.send_keys('C:/path/to/file.txt')

# 等待一段时间,以便文件上传完成
driver.implicitly_wait(10)

# 其他操作...

请注意,上述示例代码中的文件路径是本地文件路径,你需要将其替换为你自己的文件路径。另外,还可以使用绝对路径或相对路径来指定文件路径。

Selenium 自动化文件上传:隐藏元素的处理

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

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