第0008题:一个HTML文件,找出里面的正文。
在Beautiful Soup 4.2.0 文档里面有现成的例子。
#! /usr/bin/env python
#coding=utf-8
from bs4 import BeautifulSoup as BS
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BS(html_doc, 'lxml')
print soup.get_text()
get_text()
方法会得到文档中所有文字内容。
对于网页上的HTML,可以使用BeautifulSoup来解析
#! /usr/bin/env python
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import re
url = 'your url'
proxies = {
"http": "your http proxy",
"https": "your https proxy",
}
html = requests.get(url, proxies=proxies)
soup = BeautifulSoup(html.text, "html.parser", from_encoding="utf-8")
print soup.get_text().encode('ascii', 'ignore').decode('ascii')
这里有个编码解码的问题,另一篇文章再谈。