[英]How to add javascript to html using beautiful soup?
我正在使用漂亮的汤来编辑html文件。 我已经可以添加标签,但是我无法在script元素中添加我的javascript代码。
我有以下代码:
soup = BeautifulSoup(differencehtml, 'html.parser')
# create a new tag
tag = soup.new_tag("script")
tag.append = jscodestring # this is not adding the javascript to the html file
# tag.string = jscodestring # also tried this unsuccesfully
head = soup.find('head')
#insert new tag after head tag
head.insert_after(tag)
当我检查生成的html时,它看起来像这样:
...
</head>
<script>
</script>
...
为什么附加不起作用? 如何在script标签内获取代码?
Append()用于修改标签的内容。 在此处查看文档, 网址为https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring-and-new-tag 。
这行代码:
tag.append = jscodestring # this is not adding the javascript to the html file
需要看起来像这样
tag.append(jscodestring) # this is not adding the javascript to the html file
即便如此,这样做只会在标签内容内放置一个等于jscodestring的字符串值。
您要做的是向脚本标签添加一个新属性。
可以这样做。 我看不到differencehtml的内容,所以不能确定。
soup.find('script')['selected'] = '<path to your javascript file>'
检查此帖子的另一个示例, BeautifulSoup-向tag添加属性 。
(编辑)使代码看起来像这样
<script> Hello World!</script>
您只需要执行tag.append("Hello World!")
或tag.append("Hello World!")
字符串的变量放在append()内
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.