python 爬取csdn网页并保存博客到本地
来源:互联网 发布:小乌龟画图软件 编辑:程序博客网 时间:2024/03/29 22:30
这几天一直在学用python爬网页 , 现在是用urllib2,cookie等模块获取了csdn的博客源码,然后打算把所有博客都保存到本地;这就涉及到了解析html, 由于对正则的理解不太深。。。就用了第三方工具模块:美丽的汤---BeautifulSoup ,可以自己百度安装,使用教程,很容易上手: 代码不健壮。。主要是容易出现乱码。。 有时候遇到全角的时候也会出bug,以后再完善吧。
先贴张保存到本地的图:
源码如下:希望那里写的不好,多多指正。。一块学习。PS:后来才知道,这可以刷访问量(非本意。。。)
# -*- coding: utf-8 -*-import urllib,urllib2,cookielib,re,socketimport os,sys,timefrom bs4 import BeautifulSoup#防止编码乱码#reload(sys) sys.setdefaultencoding('utf-8') ####url='http://blog.csdn.net/shomy_liu'# csdn的账号headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0' }#读取htmmldef login(url=url):#socket.setdefaulttim #单位为秒time.sleep(0.5)# 防止封IPreq= urllib2.Request(url=url,headers=headers)return urllib2.urlopen(req).read()state=Truehtml=login()while state:soup=BeautifulSoup(html)articals=soup.findAll('div',{'class' : 'list_item article_item'})for artical in articals:title=artical.find('a')artical_url='http://blog.csdn.net/'+title['href']s=title.text.replace('\r\n',' ')#去掉回车符print ss=s.lstrip()#去掉首空格s=s.rstrip()#去掉尾空格f=file("D:\\study\\python\\py\\csdn_blog\\shomy_liu\\"+s+'.htm', 'w')#保存的目录f.write(login(artical_url))f.close()#print artical_url##换页转换pagelist= soup.find(name='div',id='papelist')next=pagelist.findAll('a')state=Falsefor i in next :if i.text.encode('utf-8')==str('下一页') :url='http://blog.csdn.net/'+i['href']html=login(url)state=Truebreak;
0 0
- python 爬取csdn网页并保存博客到本地
- python抓取网页中图片并保存到本地
- python抓取网页中图片并保存到本地
- python小试牛刀之爬取网页文本内容保存到本地
- Scrapy爬取网页并保存到数据库中
- python第一个爬虫小程序以及遇到问题解决(中文乱码)+批量爬取网页并保存至本地
- 简单的python爬取网页字符串内容并保存
- Python 爬虫多线程爬取美女图片保存到本地
- python 爬取网页中的图片到本地
- python 爬取网页中的图片到本地
- python 爬取网页中的图片到本地
- 使用url读取csdn的博客访问量并将记录保存到本地
- python 保存网页图片到本地
- Python:转码并保存到本地
- Python爬取CSDN博客
- 利用Python3对网易的某个话题进行爬取并保存图片到本地
- Python3 爬虫实战(一)——爬取one每日一句,并保存到本地
- [Python]使用Scrapy爬虫框架简单爬取图片并保存本地
- Joomla 3.x 在安装过程中创建数据表卡住
- BZOJ3156 防御准备
- Java对blob文件的保存和解析
- mongodb启动数据库失败(如何正确关闭mongo数据库)
- boost::string or boost::regex
- python 爬取csdn网页并保存博客到本地
- 重温线性代数(1)——线性组合
- 开放的书名检索库
- Iptables的原理和配置
- 逆波兰
- 应用开发者指南_source
- lua中面向对象(class)实现探索(一)
- Mybatis框架提供的resultMap返回值别名
- Freemarker 没有continue