question No. 0008: An HTML file to find the text inside.
Idea: I understand the text here as the main content of the Web page, then how to crawl this main content? My first idea is to use BeautifulSoup to parse the Web page, but also think that if you want to extract the text, this also involves more complex algorithms, and for different Web pages may not be very good effect. Later I found Python-goose (Github) This artifact, which is based on NLTK and beautiful soup, respectively, is the leader of text processing and HTML parsing, the goal is to give any information article or any article class page, not only extracts the main body of the article, At the same time extract all meta-information and pictures and other information, support the Chinese web page (using stuttering participle). This just fits the demand, so it's used directly.
To install Python goose:
- git clone https://github.com/grangier/python-goose.git
- CD Python-goose
- Pip Install-r requirements.txt
- Python setup.py Install
0008. Extract the contents of the HTML body. py
#!/usr/bin/env python#coding: Utf-8 fromGooseImportGoose fromGoose.textImportStopwordschineseImportSysreload (SYS) sys.setdefaultencoding ("Utf-8")# URL of the page to parseURL =' http://www.ruanyifeng.com/blog/2015/05/thunk.html ' def extract(URL): " Extract page Body"g = Goose ({' Stopwords_class ': Stopwordschinese}) Article = G.extract (Url=url)returnArticle.cleaned_textif__name__ = =' __main__ ':PrintExtract (URL)
Take Ruan Yi Feng blog on an article test, the effect is as follows:
Python show-me-the-code No. 0008 Extract HTML body content