学习Python中Selenium模块的基本用法(9:元素操作-3)

发布于:2025-09-03 ⋅ 阅读:(25) ⋅ 点赞:(0)

  Selenium模块不支持与文件上传对话框交互,但是如果是类型为 file 的 input 元素,可以使用send keys方法发送上传文件的完整路径。本文学习并验证使用Selenium模块上传文件的基本用法。
  上传文件最关键是找到类型为file的input元素,可以通过css选择器查找,也可以通过元素id或class值查找,找到input元素后将文件路径发送给该元素,如果有上传按钮,则再找到上传按钮元素并模拟点击事件。
  百度“免费在线文字识别”,找到参考文献6和7的免费在线识别上传图片中的文字网站,这两个网站支持上传图片识别其中的文字,同时不需要点击上传按钮,
  首先是参考文献6,如下图所示,分析网页结构,找到类型为file的input元素(圈红处)。编写模拟上传程序,程序运行效果如下所示。

在这里插入图片描述

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import os

driver = webdriver.Chrome()
driver.get("https://www.gaitubao.com/tupian-wenzi/")

time.sleep(2)

upload_file = os.path.abspath('C:\\Users\\XX\\Videos\\test.jpg')
file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys(upload_file)

在这里插入图片描述
  接着是参考文献7,如下图所示,分析网页结构,找到类型为file的input元素(圈红处)。编写模拟上传程序,程序运行效果如下所示。
在这里插入图片描述

driver = webdriver.Chrome()
driver.get("https://www.toolapi.cc/ocr/")

time.sleep(2)

upload_file = os.path.abspath('C:\\Users\\XX\\Videos\\test.jpg')
file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys(upload_file)

在这里插入图片描述

参考文献:
[1]https://www.selenium.dev/zh-cn/
[2]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/
[3]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502
[4]https://registry.npmmirror.com/binary.html?path=chromedriver/
[5]https://chromedriver.chromium.org/
[6]https://www.gaitubao.com/tupian-wenzi/
[7]https://www.toolapi.cc/ocr/


网站公告

今日签到

点亮在社区的每一天
去签到