【问题标题】:Python Selenium driver.find_element().text returns empty string, but text is visible in the driver.page_sourcePython Selenium driver.find_element().text 返回空字符串,但文本在 driver.page_source 中可见
【发布时间】:2022-11-16 23:05:44
【问题描述】:

我正在尝试抓取视频的一些标题并为此使用 Selenium,但我遇到了一个问题。 driver.find_element().text 返回空字符串,但标题肯定位于给定的 XPATH 中。下面是 driver.page_source 返回的页面源代码片段:

<div class="title"><a href="/f/4n3x7e31hpwxm8"target="_blank">Big.Sky.S03E01.ITA.WEBDL.1080p</a></div>

要查找我尝试使用的标题:

title_from_url = driver.find_element(
    By.XPATH, '//div[contains(@class, "title")]/a'
    ).text

从我读过的内容来看,这可能是由于页面可能没有完全加载(我在这里没有使用任何等待条件)。之后我尝试添加等待条件甚至 time.sleep(),但它并没有改变任何东西。 <迷你问题:适当的等待状态在这里看起来如何?>

任何帮助将不胜感激。 此致, 埃德。

示例站点:https://mixdrop.to/e/4n3x7e31hpwxm8

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    在提取文本内容之前,您必须等待元素完全加载。 WebDriverWait expected_conditions 应该为此使用显式等待。
    如果元素在页面上可见并且定位器正确,这应该等待:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    wait = WebDriverWait(driver, 20)
    
    title_from_url = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[contains(@class, "title")]/a'))).text
    

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 2021-10-09
      • 2018-02-28
      • 1970-01-01
      • 2020-06-06
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多