Application code analysis for crawling web content using Python

Source: Internet
Author: User

Today, we will use this article to introduce two different ways for Python to capture web content. You can use this as a reference object to select an application method that suits your needs in actual application development.

Method 1: Use the urllib2/sgmllib package to list all URLs of the target webpage.

 
 
  1. import urllib2  
  2. from sgmllib import SGMLParser   
  3. class URLLister(SGMLParser):  
  4. def reset(self):   
  5. SGMLParser.reset(self)  
  6. self.urls = []  
  7. def start_a(self, attrs):   
  8. href = [v for k, v in attrs if k=='href']   
  9. if href:  
  10. self.urls.extend(href)  
  11. f = urllib2.urlopen("http://www.donews.com/")  
  12. if f.code == 200:  
  13. parser = URLLister()  
  14. parser.feed(f.read())  
  15. f.close()  
  16. for url in parser.urls: print url 

Method 2: Use Python to call IE to capture the url and size of all images on the target Web page Require win32com and pythoncom.

 
 
  1. import win32com.client, pythoncom  
  2. import time  
  3. ie = win32com.client.DispatchEx('InternetExplorer.Application.1')  
  4. ie.Visible = 1 
  5. ie.Navigate("http://news.sina.com.cn")  
  6. while ie.Busy:  
  7. time.sleep(0.05)  
  8. doc = ie.Document  
  9. for i in doc.images:  
  10. print i.src, i.width, i.height 

This method can use the Javascript. DHTML support of IE to automatically submit the Form and process Javascript.

The above are two different methods for capturing webpage content in Python.

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.