python python 入门学习之网页数据爬虫cnbeta文章保存
16lz
2021-01-22
需求驱动学习的动力。
因为我们单位上不了外网所以读新闻是那么的痛苦,试着自己抓取网页保存下来,然后离线阅读。今天抓取的是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'
更多相关文章
- Linux使用技巧11--Ubuntu离线安装openssh-server
- Retrofit2,okhttp3 通过拦截器(Interceptor)两种缓存(离线和在线)
- Android 科大讯飞 在线和离线语音听写
- eclipseIDE for Java EE 下 离线 安装CDT的方法