惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
G
Google Developers Blog
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
J
Java Code Geeks
P
Proofpoint News Feed
V
Visual Studio Blog
爱范儿
爱范儿
The Cloudflare Blog
博客园 - 叶小钗
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
博客园 - 聂微东
H
Help Net Security
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
量子位
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - ________囧丶殇

django系列 - 安装和新建项目 SQL - 基础 javascript刷新父页面 SQL - 约束 C语言(8) - 反转单向链表 C语言(7) - 数据结构之单向链表 C语言(6) - 各种排序算法的比较 C语言(5) - 选择排序 快速排序 C语言(4) - 插入排序 C语言(3) - 冒泡排序 归并排序 C语言(2) - 从指针开始 C语言(1) - 开始之前 python实践 - 下载文件 python补充(2) - 内置函数 python补充(1) python笔记(十) - 异常和文件处理 python笔记(九) - 类 part2 python笔记(八) - 类 part1 python笔记(七) - and和or
python实践 - 抓取网页中的图片和数据
________囧丶殇 · 2009-04-30 · via 博客园 - ________囧丶殇

主要是用了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://')==else u)+img,'d:/tmp/'+img.split('/')[-1])
    f.close() 
     

上面的代码将主题保存到了当前目录的result.txt文件里

所有的图片保存到了d:/tmp/目录