我的主 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 = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to.frame(iframe)
# your work to extract link
driver.switch_to_default_content()
对于多个 url
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) 之后
关于python - 使用 Python/Selenium 访问 iframe 中的链接并获取 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51838630/