Home  >  Article  >  Backend Development  >  Python检测网站链接是否已存在

Python检测网站链接是否已存在

WBOY
WBOYOriginal
2016-06-10 15:05:241316browse

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。

Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。

像Perl语言一样, Python 源代码同样遵循 GPL(GNU General Public License)协议。

早就听说Python语言操作简单,果然名不虚传,短短几句,就实现了基本的功能。

要检测目标网站上是否存在指定的URL,其实过程很简单:

1、获得指定网站网页的HTML代码

2、在HTML代码中查找指定的URL

3、如果存在,OK;否则,Error

整个程序引用了两个lib库,urllib2和sgmllib。

urllib2库主要定义了一些访问URL(基本通过HTTP)的函数与类。

sgmllib库主要负责解析HTML代码。

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:
if (href[].count('http://网站URL')==):
self.urls.extend(href)
links = ['http://www.google.com/',
'http://www.baidu.com',
'http://www.sohu.net',
'http://www..com',
'http://www.cnblogs.com',
'http://www.qq.com',
'http://www.yahoo.com/',
'http://www.bing.com/',
'http://www..com',]
for eachlink in links:
f = urllib.urlopen(eachlink)
if f.code ==:
parser = URLLister()
parser.feed(f.read())
f.close()
if (len(parser.urls)>=):
print 'The link from '+eachlink+' is OK!'
else:
print 'The link from '+eachlink+' is ERROR!'

这其中几个主要函数:

1、urllib2.urlopen(url[, data][, timeout])//打开一个URL

2、SGMLParser.feed(data) //获得需要解析的HTML数据

3、SGMLParser.start_tag(attributes) //指定需要解析的HTML标签,在本程序中,我们调用了start_a,说明我们需要解析HTML代码中标签。通过查找标签中href属性的value,可以获得该网页上所有链接的信息,只要我们指定的URL存在,就OK了。

这其实是一个很小的脚本,但也让我激动不已。一来,我已经跨进了Python的世界,并用它解决了实际工作中的问题,二来,它的简单语法、缩进格式着实让我眼前一亮。今后,希望能够多多使用Python,解决实际工作中的种种问题,做到学以致用.

以上内容是针对Python检测网站链接是否已存在的相关介绍,希望对大家有所帮助!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn