一.首先講一下統一資源定位符,簡單的Web應用被稱為URL(統一資源定位器,Uniform Resource Locator)的web地址。URL是大型標識符URI(統一資源標識,Uniform Resource Identifier)的一部分。
網絡定位元素:
1.部件:描述
2.user:登錄名
3.password:用戶的密碼
4.host:web服務器運行的機器名或地址
5.port:端口號
二.urllib2模塊
urllib2是python的一個獲取url(Uniform Resource Locators,統一資源定址器)的模塊。它用urlopen函數的形式提供了一個非常簡潔的接口。這使得用各種各樣的協議獲取url成為可能。它同時 也提供了一個稍微復雜的接口來處理常見的狀況-如基本的認證,cookies,代理,等等。這些都是由叫做opener和handler的對象來處理的。
import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()
三.下面是一個通過訪問yago的提供的接口來統計wiki中數據在yago中的覆蓋率實例
def coveragerate(infile,outfile):
rfile = open(infile,'r')
wfile = open(outfile,'wa+')
unfindcount = 0.0
while(1):
line = rfile.readline()
tmpline = line
if not line:
break
line = line.split(' ')
URL = 'https://d5gate.ag5.mpi-sb.mpg.de/webyagospotlx/WebInterface?passedQuery=I%3A0%09S%3A'
for i in range(len(line)):
if i == 0:
URL += line[i].strip()
else:
URL += '%20' + line[i].strip()
URL += '%3B'
print URL
req = urllib2.Request(URL)
try:
response = urllib2.urlopen(req)
except URLError,e:
print e.reason
html = response.read().split('\n')
for i in range(len(html)):
if '</div><h2>Results</h2>There were no results.<P>' in html:
unfindcount += 1.0
wfile.write(tmpline.strip() + ' Flase'+'\n')
print 'run'
break
else:
wfile.write(tmpline.strip() + ' True'+'\n')
print 'run'
break
covrate = 1.0 - (unfindcount/len(html))
wfile(covrate)
wfile.close()
rfile.close()
通過觀察yago在進行查詢的時候URL的變化規則,來補全URL,在進行訪問就可以獲得該頁面的html源碼。最后通過分析源碼,來判斷是否被查詢到,最后在統計一下能夠被覆蓋的數據即可。