【问题标题】:scraping iframe data table inserted using javascript抓取使用 javascript 插入的 iframe 数据表
【发布时间】:2019-09-27 15:39:22
【问题描述】:

试图抓取数据表位于动态加载的 iframe 中的站点。 url 永远不会改变,我使用 selenium 导航到表格。但是一旦到了那里,它仍然找不到 ID 为“theiframe”的 iframe。我看到 iframe 使用了检查元素,但是当我使用我的脚本时它没有找到它。

我尝试通过 xpath (("//iframe[@id='theiframe']") 和 css 选择器 ("theiframe") 定位 iframe 来进行抓取。仍然收到一条消息说它找不到元素

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
import time

myURL = "http://www.1line.williams.com/Transco/index.html"

driver = webdriver.Firefox()

driver.get(myURL)
time.sleep(3)

action = ActionChains(driver)
step1 = 
driver.find_element_by_xpath('//div[4]/ul[1]/li[5]/a[1]')
action.move_to_element(step1).perform()
print("got to notice...waiting for menu")
time.sleep(1)
step2 = driver.find_element_by_xpath("//div[4]/ul[1]/li[5]/ul[1]/li[1]/a[1]")
action.move_to_element(step2).perform()
step2.click()

time.sleep(4)

# page_source = driver.find_element_by_xpath("//iframe[@id='theiframe']")

page_source = driver.find_element_by_id("theiframe")
print(page_source)

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver web-scraping


    【解决方案1】:

    页面上有嵌套的iframe。您需要同时切换到iframes

    第 1 帧:ID='interiorFrame'

    第 2 帧:ID='theiframe'

    为两帧引入WebDriverWaitframe_to_be_available_and_switch_to_it()

    试试下面的代码。

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium import webdriver
    
    driver = webdriver.Firefox()
    driver.get("http://www.1line.williams.com/Transco/index.html")
    action = ActionChains(driver)
    step1=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[4]/ul[1]/li[5]/a[1]")))
    action.move_to_element(step1).perform()
    step2=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[4]/ul[1]/li[5]/ul[1]/li[1]/a[1]")))
    action.move_to_element(step2).click(step2).perform()
    WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,'interiorFrame')))
    WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.ID,'theiframe')))
    page_source=driver.page_source
    print(page_source)
    

    【讨论】:

    • KunduK,很接近,但在 html 中,它只是说“正在加载”: 重要通知
      正在加载...
    • @SMJune : 该网站不允许 bot 频繁访问该页面。等待一段时间或将浏览器更改为 chrome。它会工作。
    • 太棒了!!!如果它解决了您的问题,请接受此答案。谢谢!!!
    • 谢谢...只是检查我是否可以在其中找到下载链接,是的,我找到了。谢谢!!!
    猜你喜欢
    • 2022-01-13
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多