【问题标题】:Add content to iframe with BeautifulSoup使用 BeautifulSoup 将内容添加到 iframe
【发布时间】:2016-10-05 09:12:37
【问题描述】:

假设我有以下 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] 超出索引

【问题讨论】:

  • 要替换iframe标签中的全部内容吗?
  • 可以,但不破坏标签

标签: python iframe beautifulsoup


【解决方案1】:

只需设置.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>

【讨论】:

  • 即使替换不只是一个字符串,您是否知道我可以通过任何方式做到这一点?
  • @LetsPlayYahtzee 你的意思是 repl 字符串实际上是一个 HTML sn-p 吗?
  • 是的,我开了一个新的question 与此相关
【解决方案2】:

这将适用于您替换 iframe 标记内容。

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

soup = BeautifulSoup(s, convertEntities=BeautifulSoup.HTML_ENTITIES)
show= soup.findAll('iframe')[0]
show.replaceWith('<iframe src="http://www.w3schools.com">this is the replacement</iframe>'.encode('utf-8'))
html = HTMLParser()
print html.unescape(str(soup.prettify()))

输出:

<!DOCTYPE html>
<html>
 <body>
  <iframe src="http://www.w3schools.com">my text</iframe>
 </body>
</html>

【讨论】:

  • 我正在寻找一种无需再次创建标签的方法,您知道类似的事情吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
相关资源
最近更新 更多