如何识别元素并使用 python 通过 selenium 调用 send_keys

How to identify an element and invoke send_keys through selenium with python

<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")

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

我的代码在上面,但它不起作用 如何在上面的上传按钮代码中找到元素

要查找元素并调用 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")
    
  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")