首页 > 解决方案 > Python selenium:无法定位元素(//input[@type='file']')

问题描述

我正在尝试使用 python 自动化上传文件。当我尝试执行下面的代码时,python selenium 会引发错误。即使我尝试等待 10 秒以避免同步问题。

driver.execute_script('window.open("https://ocr.space/" , "new window")')
Imagepath = r"C:\User\Desktop\banner.png"
field=driver.find_element_by_xpath('//input[@type="file"]')
field.send_keys(Imagepath)

NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//input[@type="file"]"}

网址:

https://ocr.space/

HTML 片段:

<div class="span8">
  <input type="file" id="imageFile" class="form-control choose valid">
</div>

标签: pythonhtmlseleniumautomation

解决方案


更改代码以启动 urlget似乎可以解决问题。

from selenium import webdriver


driver = webdriver.Chrome("./chromedriver")

driver.get("https://ocr.space/")
image = r"C:\Users\Thanthu Nair\Desktop\soc360.png"
field=driver.find_element_by_xpath('//input[@type="file"]')
field.send_keys(image)

还要确保提供的路径C:\User\Desktop\banner.png是正确的,否则你会得到另一个异常。这只是我的假设,该路径可能是错误的,因为通常桌面文件夹位于用户名文件夹内,用户名位于用户文件夹内。在这种情况下,根据您提供的路径,您的 Desktop 文件夹位于 User 文件夹中。


推荐阅读