首页 > 解决方案 > Python Selenium 在 Facebook 上找不到添加照片和视频按钮元素

问题描述

我正在尝试将图像上传到 Facebook,但无法单击添加照片和视频按钮。

当我查看 html 时,这是我试图点击的元素:

<input aria-label="Add Photo or Video" accept="video/*,  video/x-m4v, 
video/webm, video/x-ms-wmv, video/x-msvideo, video/3gpp, video/flv, 
video/x-flv, video/mp4, video/quicktime, video/mpeg, video/ogv, .ts, .mkv, 
image/*, image/heic, image/heif" containerclassname="_5g_r" multiple="" 
name="composer_photo[]" display="inline" role="button" tabindex="0" data- 
testid="media-sprout" type="file" class="_n _5f0v" id="js_17y">

我试图通过 id 找到元素:

driver.find_elment_by_id("js_17y").click()

我得到:

selenium.common.exceptions.NoSuchElementException: Message: no such element

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


Facebook是通过ReactJS构建的,因此click()您需要在元素上诱导WebDriverWait以使该元素可点击,并且您可以使用以下任一定位器策略

  • 使用css_selector

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[aria-label='Add Photo or Video'][name^='composer_photo'][data-testid='media-sprout']"))).click()
    
  • 使用xpath

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@aria-label='Add Photo or Video' and starts-with(@name, 'composer_photo')][@data-testid='media-sprout']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

推荐阅读