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  class="sister" id="link1">Elsie</a>,
<a  class="sister" id="link2">Lacie</a> and
<a  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')

這里有個編碼解碼的問題,另一篇文章再談。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容