python - Selenium 未找到特定元素

标签 python selenium selenium-webdriver web-scraping

执行 flickr.com 搜索 ( https://www.flickr.com/search/?text=lake ) 后,我尝试导航到“人物”部分。

我无法在 <div id="content"> 中找到元素(HTML 图像中从顶部算起的第 6 行)。基本上,无论我尝试什么,NoSuchElementException被抛出。

#! python3

# Saves photos to file from flickr.com using specified search term

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

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - \
%(levelname)s - %(message)s")

def flickr_images():
    try:
        search_term, number_images = sys.argv[1:]
    except:
        print("Something went wrong. Command line input must be of \
    format: 'filename searchterm numbermessages'")
        return

    driver = webdriver.Firefox()
    driver.get("https://www.flickr.com/")

    # wait for page to load
    WebDriverWait(driver, 10).until(EC.presence_of_element_located(\
        (By.ID, "search-field")))

    # find search text field and input search term
    driver.find_element_by_id("search-field").send_keys(search_term)

    # find and click search button
    driver.find_element_by_class_name("search-icon-button").click()

    WebDriverWait(driver, 5)

    content = driver.find_element_by_id("content")
    content.find_element_by_class_name("search-subnav-content")

if __name__ == "__main__":
   flickr_images()

enter image description here

最佳答案

我会直接导航到搜索结果页面并等待结果出现:

driver.get("https://www.flickr.com/search/?text=" + search_term)

# wait for the search results to appear
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "search-photos-results")))

content = driver.find_element_by_id("content")
content.find_element_by_class_name("search-subnav-content")

关于python - Selenium 未找到特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40403152/

相关文章:

python - 如何通过 Python 访问 Windows 屏幕键盘配件

javascript - 表单提交与使用 ajax 传递数据的按钮 - 一个有效,另一个无效

python - 如何将 .png 嵌入到 HTML 电子邮件中?

java - 我可以使用 TestNG 中的 @Parameters 从用户定义的 xml 中读取而不是从 testng.xml 中读取吗

python - 使用远程驱动程序设置 chrome 选项

c# - 使用 Selenium2,如何检查页面上是否存在某些文本?

java - 如何在 Selenium Java 代码中使用 By.parameter?

python - 使用 Cython 重载 Python 数学函数

python - Selenium - Firefox 的 MoveTargetOutOfBoundsException

html - 如何为不同 HTML 标记显示的相同文本编写通用 XPath?