#!/usr/bin/env python
#
 -*- coding: GBK -*-

import urllib

from sgmllib import SGMLParser

class URLLister(SGMLParser):
    
def reset(self):
        SGMLParser.reset(self)
        self.urls 
= []
        
    
def start_a(self, attrs):
        href 
= [v for k, v in attrs if k == 'href']
        
if href:
            self.urls.extend(href)
    
url 
= r'http://www.sinc.sunysb.edu/Clubs/buddhism/JinGangJingShuoShenMo/'
sock 
= urllib.urlopen(url)
htmlSource 
= sock.read()
sock.close()
#print htmlSource
= file('jingangjing.html''w')
f.write(htmlSource)
f.close()

mypath 
= r'http://www.sinc.sunysb.edu/Clubs/buddhism/JinGangJingShuoShenMo/'

parser 
= URLLister()
parser.feed(htmlSource)

for url in parser.urls:
    myurl 
= mypath + url
    
print "get: " + myurl
    sock2 
= urllib.urlopen(myurl)
    html2 
= sock2.read()
    sock2.close()
    
    
# 保存到文件
    print "save as: " + url
    f2 
= file(url, 'w')
    f2.write(html2)
    f2.close()

[] 的语法是 python 中的 list comprehension, 用于构造一个列表。

href = [v for k, v in attrs if k == 'href']
大致上相当于:

href = []
for k,v in attrs:
if k == 'href':
href.append(v)

相关文章:

  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
  • 2021-11-04
  • 2021-12-01
  • 2021-08-24
  • 2022-02-27
猜你喜欢
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
  • 2021-06-11
相关资源
相似解决方案