python实践 - 抓取网页中的图片和数据
2009-04-30 10:23
766 查看
主要是用了SGMLParser和urllib模块
#!/usr/lib/python
# getimg.py
import sys,os
from sgmllib import SGMLParser
type = sys.getfilesystemencoding()
class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.is_Contant=""
self.titles=[]
self.imgs=[]
def start_div(self, attrs):
href = [v for k, v in attrs if k=='class']
if href:
if href[0] == 'posttitle':
self.is_Contant=1
def end_div(self):
self.is_Contant=""
def start_img(self,attrs):
href = [self.imgs.append(v) for k, v in attrs if k=='src']
def handle_data(self, text):
if self.is_Contant:
text = text.decode('UTF-8').encode(type)
self.titles.append(text)
if __name__ == "__main__":
import urllib
u = 'http://www.cnblogs.com'
usock = urllib.urlopen(u)
parser = URLLister()
parser.feed(usock.read())
usock.close()
parser.close()
f = file('result.txt', 'w')
for title in parser.titles:
print title
f.write(title+'\r\n')
for img in parser.imgs:
urllib.urlretrieve(('' if img.find('http://')==0 else u)+img,'d:/tmp/'+img.split('/')[-1])
f.close()
上面的代码将主题保存到了当前目录的result.txt文件里
所有的图片保存到了d:/tmp/目录
#!/usr/lib/python
# getimg.py
import sys,os
from sgmllib import SGMLParser
type = sys.getfilesystemencoding()
class URLLister(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.is_Contant=""
self.titles=[]
self.imgs=[]
def start_div(self, attrs):
href = [v for k, v in attrs if k=='class']
if href:
if href[0] == 'posttitle':
self.is_Contant=1
def end_div(self):
self.is_Contant=""
def start_img(self,attrs):
href = [self.imgs.append(v) for k, v in attrs if k=='src']
def handle_data(self, text):
if self.is_Contant:
text = text.decode('UTF-8').encode(type)
self.titles.append(text)
if __name__ == "__main__":
import urllib
u = 'http://www.cnblogs.com'
usock = urllib.urlopen(u)
parser = URLLister()
parser.feed(usock.read())
usock.close()
parser.close()
f = file('result.txt', 'w')
for title in parser.titles:
print title
f.write(title+'\r\n')
for img in parser.imgs:
urllib.urlretrieve(('' if img.find('http://')==0 else u)+img,'d:/tmp/'+img.split('/')[-1])
f.close()
上面的代码将主题保存到了当前目录的result.txt文件里
所有的图片保存到了d:/tmp/目录
相关文章推荐
- python 入门实践之网页数据抓取
- python3 抓取网页自有图片
- python抓取网页图片
- 《与小卡特一起学Python》Code3 抓取网页中的某个数据
- Python爬虫抓取网页图片
- python抓取网页中图片并保存到本地
- 黄聪:python访问抓取网页常用命令(保存图片到本地、模拟POST、GET、中文编码问题)
- 一个简单的使用python抓取网页中的水文数据的程序
- Python网页抓取与爬虫基本实践-入门篇
- python的BeautifulSoup实现抓取网页数据
- Python爬虫学习笔记二:百度贴吧网页图片抓取
- 利用python正则表达式抓取网页中的图片到本地
- 抓取网页数据、下载网络图片
- 用python进行分布式网页数据抓取(二)—— 核心问题讨论
- python 抓取的网页数据中文以16进制形式显示如“\x54\76”
- python 解析网页,将抓取到的图片保存到本地
- python抓取网页图片 python爬虫实例
- python学习--抓取一个网页上图片
- 利用python抓取网页图片
- python-抓取数据、下载图片(正则)、构造headers、urlencode、get_post