Python練手項目0008

本項目採用的是https://github.com/Yixiaohan/show-me-the-code中所提供的練習項目,所有代碼均爲原創,轉載請註明,謝謝。


問題描述:練習0008的問題是你有一個網頁,需要將網頁的正文提取出來。具體代碼如下:

# -*- coding: utf-8 -*-
"""
Created on Mon Jan 09 13:10:54 2017


@author: sky
"""


import requests
from bs4 import BeautifulSoup
import codecs


url='http://www.baidu.com'
html=requests.get(url)


soup=BeautifulSoup(html.text)
a = soup.body.text.encode('GBK','ignore').decode('GBK')
b = a.encode('utf-8')
file = codecs.open('1.txt','w')
file.write(b)
file.close()


print a


注意:利用beautifulsoup可以進行簡單的文字提取

但是提取出的結果爲Unicode,需要用codercs進行轉換

詳細代碼和結果,可以參考https://github.com/g8015108/exercise-for-python

Unicode可以參考http://www.cnblogs.com/jackge/archive/2013/06/04/3117352.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章