0

目的は、infile (html) を検索し、wget に渡すことができる outfile 内の画像の URL を再現することです。これは、私が Python で書いた最初の有用なものであり、Fedora でうまく動作するようです。特にこのようなものはどこにも見つかりませんでした。これを改善するための提案はありますか?

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')
4

1 に答える 1

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)
于 2013-08-01T23:01:49.023 に答える