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

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