Created
April 26, 2017 21:12
-
-
Save tecnodur/4d8870e24c2f634137d28c2b16e4b7b2 to your computer and use it in GitHub Desktop.
Get all text from html page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/questions/328356/extracting-text-from-html-file-using-python | |
import urllib | |
from bs4 import BeautifulSoup | |
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment