2016-02-29 98 views
1

是否有任何方式使用python獲取網站中的所有鏈接,而不僅僅是在網頁中?我想這個代碼,但是這是給我只能在網頁鏈接使用python獲取avalibale在網站中的所有鏈接?

import urllib2 
import re 

#connect to a URL 
website = urllib2.urlopen('http://www.example.com/') 

#read html code 
html = website.read() 

#use re.findall to get all the links 
links = re.findall('"((http|ftp)s?://.*?)"', html) 

print links 
+0

你是什麼意思與「中的所有鏈接網站不僅在網頁上「?你的意思是存儲在www.example.com上的任何html頁面中包含的每一個鏈接? – syntonym

+0

是的,這就是我的意思 –

+0

你不能那樣做。你甚至可能無法訪問所有的html頁面。但是,您可以遞歸訪問您收集的鏈接(如果他們也指向www.exmaple.com或者它們是相對鏈接)並從那裏獲取所有鏈接。然而,這可能不是「全部鏈接」,例如如果頁面example.com/jfifjfi中沒有鏈接指向您將無法訪問該頁面。 – syntonym

回答

0

訪問遞歸你收集的鏈接,太廢以下頁面:

import urllib2 
import re 

stack = ['http://www.example.com/'] 
results = [] 

while len(stack) > 0: 

    url = stack.pop() 
    #connect to a URL 
    website = urllib2.urlopen(url) 

    #read html code 
    html = website.read() 

    #use re.findall to get all the links 
    # you should not only gather links with http/ftps but also relative links 
    # you could use beautiful soup for that (if you want <a> links) 
    links = re.findall('"((http|ftp)s?://.*?)"', html) 

    result.extend([link in links if is_not_relative_link(link)]) 

    for link in links: 
     if link_is_valid(link): #this function has to be written 
      stack.push(link) 
+0

如果link_is_valid(鏈接):#此函數必須寫入 NameError:名稱'link_is_valid'未定義 –

+0

是的。因此我寫了「#這個函數必須寫」作爲評論。您必須檢查a)您是否已經訪問過該鏈接b)如果您甚至想要訪問該鏈接(即它是否鏈接到您想要訪問的頁面「example.com」,或者它是否鏈接到例如wikipedia)c)如果您可以訪問它(目前你正在獲得ftp鏈接,我不認爲urllib2可以處理它們?)。 – syntonym

相關問題