python - 如何在 Selenium 和 Python 中使用类型查找元素

标签 python python-3.x selenium selenium-webdriver selenium-chromedriver

我有以下 html 代码。

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

我正在尝试使用 Selenium 和 Python 找到"file"和“提交”这两个元素。下面是我尝试使用的代码。
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 查找元素。我发现 xpaths 或 css 选择器特别强大,因为它们非常通用。

路径

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

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

关于python - 如何在 Selenium 和 Python 中使用类型查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48365252/

相关文章:

java - 在同一个 Selenium 网格节点上运行 PhantomJS 和 Chrome 浏览器

python - 重置密码后的 Django 身份验证问题

python - 如何平滑类似于 d3 的 curveCardinal 方法实现的闭合线的边缘?

python-3.x - 如何使用pyplot填充阶梯曲线下的区域?

python-3.x - 如何在 PIL.ImageColor.getcolor 中添加百分比透明度(alpha)?

python - Selenium 'WebElement' 对象没有属性 'Get_Attribute'

java - Selenium moveToElement() 读取工具提示不起作用

python - 如何为递归神经网络创建滞后数据点?

python - 在 Graphql 查询中收到不兼容的实例

python - 尝试使用 subprocess.check_output 使此代码与 python 解释器无关