Show me the code_0008题

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')

这里有个编码解码的问题,另一篇文章再谈。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容