前言

拿来练手的,比较简单(且有bug),欢迎交流~

功能介绍

抓取当日的知乎日报的内容,并将每篇博文另存为一个txt文件,集中放在一个文件夹下,文件夹名字为当日时间。

使用的库

re,BeautifulSoup,sys,urllib2

注意事项

1.运行环境是Linux,python2.7.x,想在win上使用直接改一下里边的命令就可以了

2.bug是在处理 “如何正确吐槽”的时候只能获取第一个(懒癌发作了)

3.直接获取(如下)内容是不可以的,知乎做了反抓取的处理

urllib2.urlop(url).read()

所以加个Headers就可以了

4.因为zhihudaily.ahorn.me这个网站时不时挂掉,所以有时候会出现错误

 def getHtml(url):
header={'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1','Referer' : '******'}
request=urllib2.Request(url,None,header)
response=urllib2.urlopen(request)
text=response.read()
return text

4.在做内容分析的时候可以直接使用re,也可以直接调用BeautifulSoup里的函数(我对正则表达式发怵,所以直接bs),比如

 def saveText(text):
soup=BeautifulSoup(text)
filename=soup.h2.get_text()+".txt"
fp=file(filename,'w')
content=soup.find('div',"content")
content=content.get_text()

show me the code

 #Filename:getZhihu.py
import re
import urllib2
from bs4 import BeautifulSoup
import sys reload(sys)
sys.setdefaultencoding("utf-8") #get the html code
def getHtml(url):
header={'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1','Referer' : '******'}
request=urllib2.Request(url,None,header)
response=urllib2.urlopen(request)
text=response.read()
return text
#save the content in txt files
def saveText(text):
soup=BeautifulSoup(text)
filename=soup.h2.get_text()+".txt"
fp=file(filename,'w')
content=soup.find('div',"content")
content=content.get_text() # print content #test
fp.write(content)
fp.close()
#get the urls from the zhihudaily.ahorn.com
def getUrl(url):
html=getHtml(url)
# print html
soup=BeautifulSoup(html)
urls_page=soup.find('div',"post-body")
# print urls_page urls=re.findall('"((http)://.*?)"',str(urls_page))
return urls
#main() founction
def main():
page="http://zhihudaily.ahorn.me"
urls=getUrl(page)
for url in urls:
text=getHtml(url[0])
saveText(text) if __name__=="__main__":
main()

最新文章

  1. MongoDB 文档的查询和插入操作
  2. 【译】css动画里的steps()用法详解
  3. mysql 存储 emoji报错( Incorrect string value: '\xF0\x9F\x98\x84\xF0\x9F)的解决方案
  4. CSS 超出隐藏问题
  5. C#画图
  6. 转:理解 Linux 的硬链接与软链接
  7. Asynchronous
  8. oracle_查询Oracle正在执行和执行过的SQL语句
  9. 关于spingMVC使用时配置自动扫描出现的路径报错
  10. 洛谷P3343 [ZJOI2015]地震后的幻想乡 [DP,概率期望]
  11. day32 通道 数据共享 进程池
  12. 2018.11.01 NOIP训练 木棒分组(搜索+剪枝)
  13. Android-HttpClient-Get与Post请求登录功能
  14. python学习笔记11-文件操作方法
  15. AasyncTask中执行execute()还是executeOnExecutor()
  16. ubuntu下android源码的下载(最新)
  17. 精《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #5 使用checkpatch.pl检查补丁的格式
  18. 【12c OCP】CUUG OCP认证071考试原题解析(36)
  19. 网站UI分析
  20. Educational Codeforces Round 56 (Rated for Div. 2) D. Beautiful Graph 【规律 && DFS】

热门文章

  1. K-means算法及文本聚类实践
  2. 前端手札--meta标记篇
  3. Web Worker 是什么鬼?
  4. 探究JVM——运行时数据区
  5. 用程序集编写clr表值函数:把正则表达式引入数据库中
  6. JavaScript学习笔记-自定义滚动条
  7. PotPlayer 1.6.52965 美化版|视频播放器
  8. 从scrapy使用经历说开来
  9. JNI系列——C文件中使用logcat
  10. ASP.NET配置Ueditor编辑器上传图片路径