Прежде всего, WARC, или веб-архива, это архивный формат для веб-страниц. Чтение файла warc
немного сложно, поскольку содержит специальный заголовок. Предполагая, что ваш файл warc
имеет номер this format.
Вы можете использовать следующий код для загрузки, разбора и возврата словаря для каждой записи, содержащей метаданные и содержимое.
def read_header(file_handler):
header = {}
line = next(file_handler)
while line != '\n':
key, value = line.split(': ', 1)
header[key] = value.rstrip()
line = next(file_handler)
return header
def warc_records(path):
with open(path) as fh:
while True:
line = next(fh)
if line == 'WARC/1.0\n':
output = read_header(fh)
if 'WARC-Refers-To' not in output:
continue
output["Content"] = next(fh)
yield output
Вы можете получить доступ к словарю следующим образом:
records = warc_records("<some path>')
>>> next_record = next(records)
>>> sorted(next_record.keys())
['Content', 'Content-Length', 'Content-Type', 'WARC-Block-Digest', 'WARC-Date', 'WARC-Record-ID', 'WARC-Refers-To', 'WARC-Target-URI', 'WARC-Type', 'WARC-Warcinfo-ID']
>>> next_record['WARC-Date']
'2013-06-20T00:32:15Z'
>>> next_record['WARC-Target-URI']
'http://09231204.tumblr.com/post/44534196170/high-res-new-photos-of-the-cast-of-neilhimself'
>>> next_record['Content'][:30]
'Side Effects high res. New pho'
Похоже, что принятый ответ на вопрос, который вы связаны с имеет решение. Вы попробовали это? – cco
@cco первый коробка кода не печатает. – user3487667