[英]Python Regular Expression for Extrating URL
我正在研究正則表達式,並想知道如何從HTML頁面中提取URL。 我想從這一行打印出網址:
Website is: http://www.somesite.com
每次找到鏈接時,我想提取**Website is:**
之后的網址是什么**Website is:**
任何幫助將不勝感激。
這是否足夠或者您需要更具體嗎?
In [230]: s = 'Website is: http://www.somesite.com '
In [231]: re.findall('Website is:\s+(\S+)', s)
Out[231]: ['http://www.somesite.com']
您可以將每一行與正常表達式與捕獲組匹配,如下所示:
for l in page:
m = re.match("Website is: (.*)")
if m:
print m.groups()[0]
這將檢查每一行是否與模式匹配,並從中提取鏈接。
一些陷阱:
這假定“網站是”表達始終在行的開頭。 如果不是,您可以使用re.search
。
假設冒號和網站之間只有一個空格。 如果不是這樣,您可以將表達式更改為Website is:\\s+(http.*)
。
具體細節取決於您嘗試解析的頁面。
由於它很簡單,因此正則表達式可能有點過分。
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
根據我所讀到的,使用正則表達式捕獲URL很難
可能使用以下正則表達式模式對您有好處:
pat = 'Website is: (%s)' % fireball
火球是一種捕捉您在此處可以找到的URL的模式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.