This article adds the following features: [1] search for URLs with extended priority, until the queue is empty [2], write all URLs to the file [3] for URLs that are inaccessible or incorrectly accessed, try using t to process spider. py
#-*-Coding: cp936-*-import urllib, Queue, sgmllib, re, OS class URLList (sgmllib. SGMLParser): def reset (self): sgmllib. SGMLParser. reset (self) # maxsize <1 indicates infinite queue self. URLqueue = Queue. queue (maxsize =-1) def start_a (self, attrs): href = [v for k, v in attrs if k = 'href '] if href: for u in href: # determine whether the URL is correct. href must have "http: //" pat = re. compile (r'http ://(. + ?) ') # False, 0, '', [], {}, () can be regarded as False, or len () = 0 Judge list is empty if len (re. findall (pat, u) = 0: continue self. URLqueue. put (u) def getURLList (url, parser): try: URLdata = urllib. urlopen (url) parser. feed (URLdata. read () URLdata. close () failed T: return startURL = "http://www.baidu.com" parser = URLList () getURLList (startURL, parser) outfile = startURL [7: len (startURL)] + ". txt "out = open (outfile, 'W + ') try: # BFS while parser. URLqueue. empty () = False: url = parser. URLqueue. get () print url out. writelines (url + '\ n') getURLList (url, parser) finally: parser. close () out. close ()