【问题标题】:Accessing Second HTML using selenium and python to extract image使用 selenium 和 python 访问第二个 HTML 以提取图像
【发布时间】:2018-10-07 12:56:02
【问题描述】:

我必须使用 selenium 从网络中提取图像。

我必须提取存在于第二个 html 标记中的图像。有人可以帮助我指向第二个 html 标记中存在的图像。

示例 html 代码。

<html>

    <img class = "img-responsive" src="test.png">

    <html>

    <img src = 'test1.png'>

    </html>

<html>

实际路径如下:

html/body/div/div/div/div/div/iframe.embed-responsive-item/html/body/img

我尝试过使用driver.find_element_by_xpath('//*[@src]')

它给了我除了第二个 html 标签中的图像之外的所有图像。

【问题讨论】:

    标签: python selenium selenium-webdriver iframe webdriverwait


    【解决方案1】:

    从您分享的实际路径可以看出,所需元素位于&lt;iframe&gt; 中,因此您需要:

    • 诱导 WebDriverWait 以使所需的 iframe 可用并切换到它
    • 诱导 WebDriverWait 使所需的元素可见,您可以使用以下解决方案:
    • 代码块:

      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      
      # other lines of code
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='embed-responsive-item']")))
      img_src = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//html/body/img"))).get_attribute("src")
      

    【讨论】:

      【解决方案2】:

      尝试定位元素 类似于 xpath 的东西取决于索引。

      el = driver.find_element_by_xpath

      (//html)[1]//img

      (//html)[2]//img

      然后你可以提取每个图像的 src 链接/文本

      image = el.get_attribute("src")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-30
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 2020-09-06
        相关资源
        最近更新 更多