Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 将内容添加到 iframe

2024年10月17日6Terrylee

假设我有以下 iframe

 s="""" 
 <!DOCTYPE html> 
 <html> 
 <body> 
 
 <iframe src="http://www.w3schools.com">          
   <p>Your browser does not support iframes.</p> 
 </iframe> 
 
 </body> 
 </html> 
 """ 

我想用这个字符串 'this is the replacement' 替换所有内容 如果我使用

dom = BeatifulSoup(s, 'html.parser') 
f = dom.find('iframe') 
f.contents[0].replace_with('this is the replacement') 

然后我不会替换所有内容,而是只替换第一个字符,在本例中是换行符。如果 iframe 完全为空,这也不起作用,因为 f.contents[0] 超出索引

请您参考如下方法:

只需设置 .string property :

from bs4 import BeautifulSoup 
 
data = """ 
 <!DOCTYPE html> 
 <html> 
 <body> 
 
 <iframe src="http://www.w3schools.com"> 
   <p>Your browser does not support iframes.</p> 
 </iframe> 
 
 </body> 
 </html> 
""" 
 
soup = BeautifulSoup(data, "html.parser") 
frame = soup.iframe 
 
frame.string = 'this is the replacement' 
 
print(soup.prettify()) 

打印:

<!DOCTYPE html> 
<html> 
 <body> 
  <iframe src="http://www.w3schools.com"> 
   this is the replacement 
  </iframe> 
 </body> 
</html>