簡體   English   中英

如何使用漂亮的湯將javascript添加到html中?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM