我有下面的html代码.

<div align="center">
    <input type="file" name="filePath"><br>
    <input type="Submit" value="Upload File"><br>
</div>

我正在try 使用Selenium和Python查找两个元素"file"和"submit".下面是我try 使用的代码.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# create a new Firefox session
driver = webdriver.Chrome()

# Maximize the browser window
driver.maximize_window()

# Enter the url to load
driver.get("<<MY PAGE TO LOAD>>")

# Wait for the page to load
driver.implicitly_wait(5)

# find the upload file type and pass a test value
upload_field = driver.find_element_by_partial_link_text('file')
upload_field.clear()
upload_field.send_keys("test")

当我运行此代码时,我能够在Chrome浏览器中成功加载页面,但我得到以下异常.

# Exception when trying to get element by type
Traceback (most recent call last):
  File "C:\Users\TEST\Desktop\Test.py", line 33, in <module>
    upload_field = driver.find_element_by_partial_link_text('file')
  File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 453, in find_element_by_partial_link_text
    return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
  File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element
    'value': value})['value']
  File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 237, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"file"}
  (Session info: chrome=63.0.3239.132)
  (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.14393 x86_64)

我查看了提供的解决方案here,但这也是一个错误.我目前正在使用Python 3.6.4 x64和Selenium 3.8.1.我的操作系统是Windows 7 x64位.如何在html中获取带有"type"的元素?

推荐答案

在查找元素时签出the docs.我发现XPath或css Select 器特别强大,因为它们非常通用.

xpath

upload_field = driver.find_element_by_xpath("//input[@type='file']")

css Select 器

upload_field = driver.find_element_by_css_selector("input[name='filePath'][type='file']")

Python-3.x相关问答推荐

PANDAS中当前数据帧的匹配与更新

我用Kivy创建的应用程序在安卓系统上运行时出错.(attributeerror:';class';对象没有属性';_javaclass__cls_storage';)

将列表转换为 pandas 数据框,其中列表包含字典

以某种方式分割字符串

如何沿单列获取嵌套列表中的唯一值?

在 python f-string 中使用 \u

python 3.10.5 中可能存在的错误. id 函数工作不明确

使用 RANSAC 在激光雷达点云中查找电力线

使用 selenium 加速网页抓取

以编程方式映射 uniprot ID 时如何解决 400 客户端错误?

如何在带有 GUI 的 python 游戏中设置回答时间限制?

Python - 使用 OpenCV 将字节图像转换为 NumPy 数组

TimescaleDB:是否可以从 Python 调用create_hypertable?

获取比较多列的最大值并返回特定值

Python - For 循环数百万行

使用逗号时,除了处理程序中的语法无效

使用打印时,用+连接是否比用,分隔更有效?

0 是 0 == 0(#evaluates 为真?)

Python3 - 如何从现有抽象类定义抽象子类?

如何使用异步 for 循环遍历列表?