2012-04-09 89 views
0

我已經很多地跟隨了一個教程,並且我希望我的掃描器能夠清除包含每個警察局信息的特定頁面的所有鏈接,但它幾乎返回整個站點。Web掃描器將無法工作

from urllib import urlopen 
import re 

f = urlopen("http://www.emergencyassistanceuk.co.uk/list-of-uk-police-stations.html").read() 

b = re.compile('<span class="listlink-police"><a href="(.*)">') 
a = re.findall(b, f) 

listiterator = [] 
listiterator[:] = range(0,16) 

for i in listiterator: 
    print a 
    print "\n" 

f.close() 
+1

請舉你跟着教程。 – Nix 2012-04-09 19:29:23

+0

http://www.youtube.com/watch?v=Ap_DlSrT-iE我注意到他提到了beautifulsoup,但我知道我的腳本不使用它的任何功能 – 2012-04-09 19:31:14

+2

emergencyassistanceuk.co.uk將不知道他們爲什麼現在有這麼多的交通...;) – Nix 2012-04-09 19:37:45

回答

-1

這個類有超過1.6k的鏈接。

我認爲它的正常工作...是什麼讓你覺得它不工作?


,你絕對應該使用美麗的湯,這是愚蠢的簡單,非常可用。

+0

是的,但它打印的HTML,我想讓它打印標籤上的「」之間的所有內容。我認爲這個劇本就是這麼做的。 – 2012-04-09 19:35:32

+0

你應該改寫你的問題'但它返回整個網站幾乎'我的正則表達式太貪婪。 – Nix 2012-04-09 19:36:49

3

您正在使用正則表達式來解析HTML。你不應該這樣做,因爲你最終會遇到這種類型的問題。首先,.*通配符將盡可能匹配文本。但是一旦你解決了這個問題,你就會從挫敗之樹中摘下另一個水果。改爲使用適當的HTML分析器。

7

使用BeautifulSoup

from bs4 import BeautifulSoup 
from urllib2 import urlopen 

f = urlopen("http://www.emergencyassistanceuk.co.uk/list-of-uk-police-stations.html").read() 

bs = BeautifulSoup(f) 

for tag in bs.find_all('span', {'class': 'listlink-police'}): 
    print tag.a['href'] 
+0

謝謝,做了我所需要的。 – 2012-04-09 19:54:40

+3

「謝謝,只是做了我需要的。」最好表達[「通過點擊答案左邊的複選框大綱」](http://stackoverflow.com/faq#howtoask)。 – Johnsyweb 2012-04-21 00:53:17