2013-08-01 80 views
0

目的是搜索infile(html)並重現可以傳遞給wget的outfile中任何圖像的URL。這將是我用Python編寫的第一個有用的東西,它似乎在Fedora上運行良好。我找不到任何特別的地方。有沒有人有改善這方面的建議?將分隔字符串從infile寫入輸出文件

import fileinput 
import re 
#replace 'output.txt' with the name of your outfile 
file = open('output.txt', 'w') 

#prefix and postfix are how we discriminate your substring from the infile's line 
prefix = '<img src=' 
postfix = '.jpg' 

#read through the infile line-by-line 
for line in fileinput.input(): 
    if re.search(prefix, line): 
     #from if above, if you find the prefix, assign the integer to first_index 
     first_index = line.index(prefix) 
      if re.search(postfix, line): 
       #same as comment above, but for postfix 
       second_index = line.index(postfix) 
       #write your string plus an newline to the outfile 
       file.write(line[first_index+prefix.__len__():second_index+postfix.__len__()]+'\n') 
+0

這是否試圖用正則表達式解析HTML,我聞到了? – Sinkingpoint

+0

'wget -prl1 --accept = jpg ' – Phylogenesis

+0

我喜歡wget,但總是比我要求的要多。 Wget也經常抱怨一些網址並拒絕做這項工作。這仍然是我的第一次嘗試。 – Furlong

回答

0

我在過去做過這樣的事情,它工作得很好......我相信它會比試圖用正則表達式解析更準確。

from HTMLParser import HTMLParser 


class ImageFinder(HTMLParser): 
    def __init__(self): 
     HTMLParser.__init__(self) 
     self.file = open('output.txt', 'w') 
    def handle_starttag(self, tag, attrs): 
     if tag == "img": 
      url = [u[1] for u in attrs if u[0] == "src"][0] 
      self.file.write(url+"\n") 
    def __exit__(self): 
     self.file.close() 

inputdata = open("myfile.txt").read() 
parser = ImageFinder() 
parser.feed(inputdata) 
+0

啊,更清潔的解決方案! – Furlong