【问题标题】:Access the link inside iframe with Python/Selenium and get url使用 Python/Selenium 访问 iframe 内的链接并获取 url
【发布时间】:2019-01-21 03:30:21
【问题描述】:

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

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

下面是我的 主 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();

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

【问题讨论】:

  • 你不会在任何地方切换到iframe
  • @Guy 我是 Python 新手,你介意告诉我 switch to the frame 应该去哪里吗?

标签: python html selenium iframe


【解决方案1】:

你应该使用

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) 之后

【讨论】:

  • 不错! @Nihail 如果我有多个 iframe 网址怎么办?我需要更改什么才能循环所有 iframe url?以及如何只打印文本?因为现在它会打印整个 html 源代码。
  • 文字是什么?你想要哪个
  • 我的输出如下所示:&lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="http://www.test2.com" target="_blank"&gt;&lt;img src="https://https://img2.test2.com/LWBAD-1.jpg&gt;&lt;/a&gt;&lt;br /&gt;Code: LWBAD &lt;/body&gt;&lt;/html&gt; 但我只想打印出Code: LWBAD
  • ?有什么想法吗?
  • 运气不好 :( 仅在有单个 url 时有效 :( stale element reference: element is not attached to the page document
【解决方案2】:

试试这个:

iframe = driver.find_elements_by_tag_name('iframe')
for i in range(0, len(iframe)):
    f = driver.find_elements_by_tag_name('iframe')[i]
    driver.switch_to.frame(i)
    #  your work to extract link
    text = driver.find_element_by_tag_name('body').text
    print(text)
    driver.switch_to_default_content()

【讨论】:

  • 你去!但问题是什么?现在工作该死的顺利。
  • driver.switch_to_default_content()驱动器需要重新查找iframe时。所以我发现它使用f = driver.find_elements_by_tag_name('iframe')[i]
  • 我没有 IDE 来测试我的代码,否则我会从一开始就建议它。
  • 啊啊啊啊!你是男人!最后一个问题,一个简单的问题,我如何将Code: 部分从输出中剥离出来,所以我只有干净的:LWBAD
  • 每次需要删除代码:??
猜你喜欢
  • 2015-10-28
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多