python - 使用 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 的原因
解决方案
你应该使用
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)
推荐阅读
- airflow - 气流连接密码解密
- javascript - React Js - 表格不对名称进行排序
- javascript - react-responsive-carousel:如何给拇指固定高度?
- groovy - groovy lang 缺少属性异常
- java - java,计算用户输入的数字
- python - Heroku 上的 Django - 缺少静态文件 manifest.json 文件
- php - 如何在 Api-Platform 上使用带有 Messanger 输入的路径中的 {id}?
- angular - 复选框中的单击事件
- html - 拖放一个元素并放下另一个元素
- node.js - Stripe,如何在结帐会话中包含多个产品?