首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用漂亮的汤将javascript添加到html中?

如何使用漂亮的汤将javascript添加到html中?
EN

Stack Overflow用户
提问于 2018-08-30 02:41:01
回答 1查看 1.8K关注 0票数 1

我正在使用美汤来编辑一个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>
...

为什么append不起作用?如何获取脚本标记内的代码?

EN

回答 1

Stack Overflow用户

发布于 2018-08-30 03:07:36

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 - adding attribute to tag

(编辑)以使代码如下所示

<script> Hello World!</script>

您只需要执行tag.append("Hello World!")或将一个字符串变量放在append()中即可。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52084162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档