2014-04-02 14 views
29

Próbuję usunąć wszystkie html/javascript przy użyciu bs4, jednak nie pozbyć się javascript. Wciąż to widzę z tekstem. Jak mogę to obejść?BeatifulSoup4 get_text nadal ma javascript

Próbowałem użyć nltk, który działa dobrze, ale clean_html i clean_url zostaną usunięte poruszając się do przodu. Czy istnieje sposób na zupy get_text i uzyskać taki sam wynik?

Próbowałem patrząc na innych stronach:

BeautifulSoup get_text does not strip all tags and JavaScript

Obecnie używam funkcji nieaktualnych w NLTK użytkownika.

EDIT

Oto przykład:

import urllib 
from bs4 import BeautifulSoup 

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

wciąż widzę następujące dla 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(); 
}); 

Jak mogę usunąć js?

Tylko inne opcje znalazłem to:

https://github.com/aaronsw/html2text

Problem z html2text jest to, że naprawdę naprawdę powolny czasami i tworzy zauważalne opóźnienie, które jest jedno NLTK był zawsze bardzo dobre .

+0

To naprawdę pomaga, czy możemy zobaczyć (fragment) html tym javascript –

+0

Dodane przykład. – KVISH

Odpowiedz

55

oparty częściowo na 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) 
+5

zamiast 'script.extract()', lepiej użyć 'script.docompose()', które usuwa tylko bez zwracania obiektu znacznika. –

7

Aby uniknąć błędów kodowania na końcu ...

import urllib 
from bs4 import BeautifulSoup 

url = url 
html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 

# kill all script and style elements 
for script in soup(["script", "style"]): 
    script.extract() # 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.encode('utf-8')) 
Powiązane problemy