BFS keeps capturing URLs and placing them in files

Source: Internet
Author: User

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 ()

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.