2013-02-18 120 views
0

我正在處理正則表達式,並想知道如何從HTML頁面提取URL。 我想從該行打印出來的網址:提取URL的Python正則表達式

Website is: http://www.somesite.com 

每次該鏈接被發現,我只想提取什麼網址是有後**Website is:** 任何幫助將不勝感激。

回答

2

這是否足夠或您需要更具體?

In [230]: s = 'Website is: http://www.somesite.com ' 
In [231]: re.findall('Website is:\s+(\S+)', s) 
Out[231]: ['http://www.somesite.com'] 
+0

這就是如果網址周圍存在''/''標籤,那麼就會有問題。 – 2013-02-18 16:49:26

+0

我必須承認,如果是我,我會使用Google提供的ReExp食譜之一。我做了最簡單的工作。 – sotapme 2013-02-18 17:01:17

+0

謝謝。我試過這個,它工作。感謝別人對他們的大量輸入以及:) – 2013-02-18 17:10:42

0

你可以每行一個正則表達式匹配的捕獲組,就像這樣:

for l in page: 
    m = re.match("Website is: (.*)") 
    if m: 
     print m.groups()[0] 

這兩個檢查每一行匹配的模式,並從中提取的鏈接。

幾個陷阱:

  1. 這假定「網站是」表達始終是在該行的開始。如果不是,您可以使用re.search

  2. 這假定冒號和網站之間只有一個空格。如果不是這樣,你可以將表達式改爲Website is:\s+(http.*)

具體取決於您嘗試解析的頁面。

0

正則表達式可能是過度的,因爲它非常簡單。

def main(): 
    urls = [] 
    file = prepare_file("<yourfile>.html") 
    for i in file: 
     if "www" in i or "http://" in i: 
      urls.append(i) 
    return urls 


def prepare_file(filename): 
    file = open(filename) 
    a = file.readlines() #splits on new lines 
    a = [ i.strip() for i in [ x for x in a ] ] #remove white space 
    a = filter(lambda x : x != '', a) #remove empty elements 
    return a