【问题标题】:How to identify an element and invoke send_keys through selenium with python如何使用 python 通过 selenium 识别元素并调用 send_keys
【发布时间】:2025-11-21 18:15:02
【问题描述】:
<img src="images/file_explorer.png" class="browse" style="cursor: pointer;height:33px;" title="file from your computer">
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys

import time

driver = webdriver.Chrome(executable_path="C:/webdrivers/chromedriver.exe")
driver.maximize_window()
driver.get("https://www.collabera.com/find-a-job/search-jobs/?sort_by=dateposted&Posteddays=4000&searchany=QA&anylocation=usa")
time.sleep(3)
driver.find_element_by_css_selector("#srchpgbnnr > div:nth-child(1) > div:nth-child(1) > div > a").click()

driver.find_element_by_css_selector("body > section:nth-child(7) > div:nth-child(2) > div > div.col-md-offset-2.col-md-3.__jobdesc-sidebar.col-xs-hide > div > a").click()
time.sleep(15)
driver.find_element_by_css_selector("img.browse[src='images/file_explorer.png'][title='file from yourcomputer']").send_keys("C:\\Users\\user\\Desktop\\collebra.txt")

网址:https://www.collabera.com/find-a-job/search-jobs/job-details/126013-qa-analyst-jobs-ann-arbor-mi

我的代码高于一个它不起作用 如何在上面的上传按钮代码中找到元素

【问题讨论】:

  • 您确定要在&lt;img&gt; 标签上调用send_keys() 吗?
  • 你能编辑上面代码中的错误吗?
  • 看起来您正试图单击 iframe 中的元素。你可以尝试先切换到iframe然后点击上传图标吗?此外,Windows 文件上传向导是 selenium 无法处理的(使用 send_keys())。您可以使用 windows shell 脚本或 python 库(例如PyAutoIt)来处理文件上传。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:
  1. 为了能够处理文件上传表单,您需要切换到 iframe:

    driver.switch_to.frame(driver.find_element_by_class_name("apply-form"))
    
  2. 你需要处理input元素,而不是img

    driver.find_element_by_xpath("//input[@type='file']").send_keys("C:\\Users\\user\\Desktop\\collebra.txt")
    

【讨论】:

  • 没有这样的元素:无法找到元素:{"method":"xpath","selector":"//input[@type='file']"}
  • 在哪一行?您在该行之前使用了time.sleep() 吗?
  • 非常感谢我努力了 3 天
  • 太棒了。但请注意,虽然它与 time.sleep() 一起使用 time.sleep() 是一种不好的做法,但您应该尝试 explicit/implicit waits
  • 你能帮我一个忙吗?我如何在 url 中粘贴电子邮件并命名下一个:collabera.com/find-a-job/search-jobs/job-details/…
【解决方案2】:

要查找元素并调用 send_keys() 方法,您可以丢弃 time.sleep(5) 并诱导 WebDriverWait 并使用以下任何选项:

  • CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "img.browse[src='images/file_explorer.png'][title='file from your computer']"))).send_keys("C:\\Users\\user\\Desktop\\collebra.txt")
    
  • XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//img[@class='browse' and @src='images/file_explorer.png' and @title='file from your computer']"))).send_keys("C:\\Users\\user\\Desktop\\collebra.txt")
    

【讨论】:

  • not working 没有说明发生了什么错误,请使用您当前的代码试验和错误跟踪日志更新问题。