python如何获取iframe页面内容

2024-04-26

在Python中获取iframe页面内容的方法有两种:使用Requests库和使用Selenium库。

  1. 使用Requests库:
import requests

url = 'https://example.com'
response = requests.get(url)
html_content = response.text

# 使用BeautifulSoup解析html内容
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')

# 找到iframe元素
iframe = soup.find('iframe')

# 获取iframe的src属性
iframe_src = iframe['src']

# 获取iframe页面内容
iframe_response = requests.get(iframe_src)
iframe_content = iframe_response.text

print(iframe_content)
  1. 使用Selenium库:
from selenium import webdriver

url = 'https://example.com'
driver = webdriver.Chrome()
driver.get(url)

# 切换到iframe
iframe = driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(iframe)

# 获取iframe页面内容
iframe_content = driver.page_source

print(iframe_content)

# 退出浏览器
driver.quit()

以上是两种常用的方法来获取iframe页面内容,可以根据具体需求选择适合的方法。