Python-based Web Crawler implementation code Interpretation

Source: Internet
Author: User
Tags python web crawler

Python is a powerful computer programming language. It can also be seen as an object-oriented general language. It has outstanding features and greatly facilitates the application of developers. Here, let's take a look at the Python city and county web crawler methods.

Today, I saw a webpage, and it was very troublesome to read it online because I used a telephone line to access the internet at home. So I wrote a simple program to capture the web page and read it offline, saving the cost of telephone. :) this program has only one layer of structure because the pages linked to the home page are in the same directory. Therefore, some hard-coded links are written for analysis.

The Python web crawler code is as follows:

 
 
  1. #! /Usr/bin/env python
  2. #-*-Coding: GBK -*-
  3. Import urllib
  4. From sgmllib import SGMLParser
  5. Class URLLister (SGMLParser ):
  6. Def reset (self ):
  7. SGMLParser. reset (self)
  8. Self. urls = []
  9. Def start_a (self, attrs ):
  10. Href = [v for k, v in attrs if k = 'href ']
  11. If href:
  12. Self. urls. extend (href)
  13. Url = r 'HTTP: // www.sinc.sunysb.edu/Clubs/buddhism/JinGangJingShuoShenMo /'
  14. Sock = urllib. urlopen (url)
  15. HtmlSource = sock. read ()
  16. Sock. close ()
  17. # Print htmlSource
  18. F = file('jingangjing.html ', 'w ')
  19. F. write (htmlSource)
  20. F. close ()
  21. Mypath = r 'HTTP: // www.sinc.sunysb.edu/Clubs/buddhism/JinGangJingShuoShenMo /'
  22. Parser = URLLister ()
  23. Parser. feed (htmlSource)
  24. For url in parser. urls:
  25. Myurl = mypath + url
  26. Print "get:" + myurl
  27. Sock2 = urllib. urlopen (myurl)
  28. Html2 = sock2.read ()
  29. Sock2.close ()
  30. # Save to file
  31. Print "save as:" + url
  32. F2 = file (url, 'w ')
  33. F2.write (html2)
  34. F2.close ()

The above describes how to implement web crawler in Python.

Related Article

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.