Recently, I purchased several links with high PR values and linked our own website links. In order to check whether the website of the other party has put the link to our website, I wrote a small script using python, because this is my first PythonProgramFor more information, seeCode. Therefore, if there are similarities, it is purely imitation.
I have heard that the Python language is easy to operate and has been well known. In just a few words, it has implemented basic functions.
To check whether a specified URL exists on the target website, the process is simple:
1. Obtain the HTML code of the specified website webpage
2. Search for the specified URL in HTML code
3. If yes, OK; otherwise, error
The entire program references two lib libraries,Urllib2AndSgmllib.
Urllib2The library mainly defines some functions and classes for accessing URLs (basically through HTTP.
SgmllibLibrary is mainly responsible for parsing HTML code.
1 Import Urllib2
2 From Sgmllib Import Sgmlparser
3
4 Class Urllister (sgmlparser ):
5 Def Reset (Self ):
6 Sgmlparser. Reset (Self)
7 Self. URLs = []
8
9 Def Start_a (self, attrs ):
10 Href = [V For K, V In Attrs If K = ' Href ' ]
11 If Href:
12 If (Href [0]. Count ( ' Http: // website URL ' ) = 1 ):
13 Self. URLs. Extend (href)
14
15
16 Links = [ ' Http://www.google.com/ ' ,
17 ' Http://www.baidu.com ' ,
18 ' Http://www.sohu.net ' ,
19 ' Http://www.163.com ' ,
20 ' Http://www.cnblogs.com ' ,
21 ' Http://www.qq.com ' ,
22 ' Http://www.yahoo.com/ ' ,
23 ' Http://www.bing.com/ ' ,
24 ' Http://www.360.com ' ,]
25
26 For Eachlink In Links:
27 F = Urllib2.urlopen (eachlink)
28 If F. Code = 200 :
29 Parser = Urllister ()
30 Parser. Feed (F. Read ())
31 F. Close ()
32 If (LEN (parser. URLs) > = 1 ):
33 Print ' The link from ' + Eachlink + ' Is OK! '
34 Else :
35 Print ' The link from ' + Eachlink + ' Is Error! '
The following are the main functions:
1,Urllib2.Urlopen(URL[,Data] [,Timeout]) // Open a URL
2,Sgmlparser.Feed(Data) // Obtain the HTML data to be parsed
3,Sgmlparser.Start_tag(Attributes) // Specify the HTML tag to be parsed. In this program, start_a is called, indicating that the <A> tag must be parsed in the HTML code. Search for the value of the href attribute in the <A> tag to obtain information about all links on the webpage. If the specified URL exists, it will be OK.
This is actually a very small script, but it also makes me very excited. First, I have moved into the world of Python and used it to solve problems in practical work. Second, its simple syntax and indent format have really made me shine. In the future, we hope to use Python more to solve all kinds of problems in actual work and apply what we have learned.