2012-06-24 189 views
1

我正在處理一些需要我獲取頁面上所有URL的內容。它似乎可以在我測試過的大多數網站上運行,例如microsoft.com,但它只會從google.com返回三個網站。下面是相關的源代碼:獲取頁面上的所有URL Python


    import urllib 
    import time 
    import re 
    fwcURL = "http://www.microsoft.com" #URL to read 
    mylines = urllib.urlopen(fwcURL).readlines() 
    print "Found URLs:" 
    time.sleep(1) #Pause execution for a bit 
    for item in mylines: 
    if "http://" in item.lower(): #For http 
     print item[item.index("http://"):].split("'")[0].split('"')[0] # Remove ' and " from the end, for example in href= 
    if "https://" in item.lower(): #For https 
     print item[item.index("https://"):].split("'")[0].split('"')[0] # Ditto 

如果我的代碼可以改進,或者有更好的方式來做到這一點,請回復。提前致謝!

+3

你試過BeautifulSoup嗎? –

+0

獲取頁面上的所有URL基本上是一個蜘蛛... – gabeio

回答

2

首先,HTML不是一種常規語言,並且沒有任何簡單的字符串操作可以在所有頁面上運行。你需要一個真正的HTML解析器。我推薦Lxml。然後,它只是通過樹遍歷並找到你想要的元素。

其次,有些頁面可能是動態的,所以你不會在html源代碼中找到所有的內容。谷歌大量使用JavaScript和AJAX(注意它是如何顯示結果而不重新加載頁面的)。

+0

+1對於大量使用JS/Ajax的網站發表評論。 – Felix

3

嘗試使用機械化或BeautifulSoup或lxml。

通過使用BeautifulSoup,您可以輕鬆獲取所有html/xml內容。

import urllib2 
from BeautifulSoup import BeautifulSoup 
page = urllib2.urlopen("some_url") 
soup = BeautifulSoup(page.read()) 
links = soup.findAll("a") 
for link in links: 
    print link["href"] 

BeautifulSoup很容易學習和理解。

2

我會用LXML做:

import lxml.html 

page = lxml.html.parse('http://www.microsoft.com').getroot() 
anchors = page.findall('a') 

值得一提的是,如果鏈接是動態生成的(通過JS或類似的),那麼您將無法獲得這些短信以某種方式自動在瀏覽器中。