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

我正在使用漂亮的汤来编辑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 - adding attribute to tag。

(编辑)使代码看起来像这样

<script> Hello World!</script>

您只需要执行tag.append("Hello World!")或将为字符串的变量放在append()内

Javascript + Python:将数组发送到Python脚本,将结果返回给Javascript - javascript

我想建立一个网页,该网页通过Javascript API进行许多Facebook状态更新,并将它们分类到一个数组中。然后,我想将此数组发送到Python脚本,该脚本可以专门使用NLTK.进行语言分析。在Python中获得合适的结果后,我想将结果从该脚本返回到Javascript,以显示给用户等。听起来可能吗? javascript大神给出的解决方案 是的,完…

html onClick打开url存储在php变量中 - javascript

以下是我的代码,正在获取Uncaught SyntaxError: Unexpected token },但是我的代码中没有看到任何}。 window.open期望用引号引起来的url,我尝试了单引号和双引号的不同组合,但不起作用并且也无法在echo中转义双引号。请帮助谢谢..<?php $a = "https://www.google.co…

如何从脚本中提取数据? - javascript

这是包含所需数据的脚本在html页面上的样子: u'{displayName:“ iPhone 5 16GB黑色”, productNameUrl:“ apple-iphone-5-16gb黑色和平板”, _default:“ true”,优先级:“ 1”,paymMinPrice:“ 9.99”,paymMinMrc:“ 46.00”, paymMinCo…

Python:可以使用JSON将消息发送到包含加密部分的Python Server吗? - javascript

我对JSON的了解不多,我刚刚开始学习本教程,所以请多多包涵:http://pymotw.com/2/json/我的问题是我可以使用JSON发送包含已加密的部分的消息到Python服务器,以便它可以将其转发到另一台服务器吗?该消息将来自通过SSL的Javascript客户端,其中包含有关Python Server的一些信息,以及将被加密的消息转发到另一个Py…

从Chrome WebDriver访问getEventListeners(Python) - javascript

目标:从Selenium WebDriver获取附加到节点的所有事件我正在使用selenium-python,我想执行一个javascript脚本(通过driver.execute_script('my js script')。该脚本使用getEventListeners,仅在Chrome上可用。我成功使用了driver = webdri…