gpt4 book ai didi

python - BeatifulSoup4 get_text 仍然有 javascript

转载 作者:IT老高 更新时间:2023-10-28 21:32:43 27 4
gpt4 key购买 nike

我正在尝试使用 bs4 删除所有 html/javascript,但是,它并没有摆脱 javascript。我仍然在文本中看到它。我该如何解决这个问题?

我尝试使用 nltk 效果很好,但是 clean_htmlclean_url 将被删除。有没有办法使用汤 get_text 并获得相同的结果?

我尝试查看这些其他页面:

BeautifulSoup get_text does not strip all tags and JavaScript

目前我正在使用 nltk 已弃用的功能。

编辑

这是一个例子:

import urllib
from bs4 import BeautifulSoup

url = "http://www.cnn.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
print soup.get_text()

我仍然看到 CNN 的以下内容:

$j(function() {
"use strict";
if ( window.hasOwnProperty('safaripushLib') && window.safaripushLib.checkEnv() ) {
var pushLib = window.safaripushLib,
current = pushLib.currentPermissions();
if (current === "default") {
pushLib.checkPermissions("helloClient", function() {});
}
}
});

/*globals MainLocalObj*/
$j(window).load(function () {
'use strict';
MainLocalObj.init();
});

如何删除 js?

我发现的只有其他选项:

https://github.com/aaronsw/html2text

html2text 的问题在于它有时真的真的很慢,并且会产生明显的延迟,这是 nltk 一直非常擅长的一件事。

最佳答案

部分基于Can I remove script tags with BeautifulSoup?

import urllib
from bs4 import BeautifulSoup

url = "http://www.cnn.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
script.decompose() # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

关于python - BeatifulSoup4 get_text 仍然有 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22799990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com