我正在使用美汤来编辑一个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不起作用?如何获取脚本标记内的代码?
发布于 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()中即可。
https://stackoverflow.com/questions/52084162
复制相似问题