需求驱动学习的动力。

因为我们单位上不了外网所以读新闻是那么的痛苦,试着自己抓取网页保存下来,然后离线阅读。今天抓取的是cnbeta科技新闻,抓取地址是http://m.cnbeta.com/wap/index.htm?page=1,咱们需要抓取的是前5页就行了。代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2,re,time,json
import sys
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')
n=0
f = open('cnbeta.txt','a')
headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} 
mainurl="http://m.cnbeta.com/wap"

for i in range(1,5):
 add='http://m.cnbeta.com/wap/index.htm?page='+str(i)
 
 req = urllib2.Request(add, headers=headers) 
 wb=urllib2.urlopen(req).read()
 soup=BeautifulSoup(wb)

 file=open(str(i)+'cnbetamain.html','a')
 file.write(wb)
 elv1ment=soup.find_all('div',{'class':'list'})
 for elv in elv1ment:
  n=n+1
  url=elv.find('a',href=True).get('href')
  name=elv.find('a',href=True).get_text()
  print name + ','+'http://m.cnbeta.com'+url
  f.write(str(n)+','+name + ','+'http://m.cnbeta.com'+url+'\n')
  try:
   html =urllib2.urlopen(urllib2.Request('http://m.cnbeta.com'+url, headers=headers)).read()
   filename=name+'.html'
   file=open(filename,'a')
   file.write(html)
  except:
   print 'NOT FOUND'
  #print filename

  time.sleep(1)
f.close()
file.close()
print 'OVER'

更多相关文章

  1. Linux使用技巧11--Ubuntu离线安装openssh-server
  2. Retrofit2,okhttp3 通过拦截器(Interceptor)两种缓存(离线和在线)
  3. Android 科大讯飞 在线和离线语音听写
  4. eclipseIDE for Java EE 下 离线 安装CDT的方法

随机推荐

  1. Android WebView系列(二)Android和JS互调,Br
  2. Android:Animation
  3. 转:LinearLayout布局
  4. Android studio :Please configure Andro
  5. Android优秀实例源码
  6. [Android] 基于 Linux 命令行构建 Androi
  7. android点滴2
  8. Android(安卓)【真机】与【模拟器】触摸
  9. Android安全机制解析与应用实践
  10. android media库中external的读取