The Python programming language has many different application methods than other predictions we are familiar. However, the main feature of this language is that it is easy to use, so it is not difficult to learn. Here, we can take a look at the syntax of the Python constructor list.
Python constructor list syntax code example:
- #! /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
- F = 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 ()
- # Save to file
- Print "save as:" + url
- F2 = file (url, 'w ')
- F2.write (html2)
- F2.close ()
The [] syntax is list comprehension in python, which is used to construct a list in Python.
- href = [v for k, v in attrs if k == 'href']
Generally, it is equivalent:
- href = []
- for k,v in attrs:
- if k == 'href':
- href.append(v)
The above is the syntax application of the Python constructor list.