首页 > 解决方案 > 使用 Python/Selenium 访问 iframe 内的链接并获取 url

问题描述

我的主 html 页面有一个 iframe,我需要获取那里的文本Code: LWBAD

检查图片以获得更好的理解:

在此处输入图像描述

Bellow 是我的主要 html 页面源代码,其中包含一个 iframe:

<td class="centerdata flag"><iframe style="width: 200px; height: 206px;" scrolling="no" src="https://www.example.com/test/somewhere" ></iframe></td>

重定向链接(iframe 页面)有这个html 源

<body>
<a href="http://www.test2.com" target="_blank">
<img src="https://img2.test2.com/LWBAD-1.jpg"></a>
<br/>Code: LWBAD

到目前为止,我可以从我的主 html 页面获取完整的页面源代码。

from bs4 import BeautifulSoup
from selenium import webdriver
import time
import html5lib

driver_path = '/usr/local/bin/chromedriver 2'
driver = webdriver.Chrome(driver_path)
driver.implicitly_wait(10)

driver.get('http://example.com')
try:
    time.sleep(4)
    iframe = driver.find_elements_by_tag_name('iframe')
    driver.switch_to_default_content()

    output = driver.page_source

    print (output)

finally:
    driver.quit();

*网址无法从我的网络外部访问,这就是我使用 example.com 的原因

标签: pythonhtmlseleniumiframe

解决方案


你应该使用

iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to.frame(iframe)
 #  your work to extract link
driver.switch_to_default_content()

对于多个网址

find_elements_by_tag_name将返回一个数组。所以使用 for 循环

iframe = driver.find_elements_by_tag_name('iframe')
for i in iframe:
    driver.switch_to.frame(i)
    #  your work to extract link
driver.switch_to_default_content()

只获取文本

利用

text = driver.find_element_by_tag_name('body').text

driver.switch_to.frame(i)


推荐阅读