簡體   English   中英

如何在Python中讀取與文件中的起始模式匹配的一大塊行?

[英]How to read a chunk of lines that match a starting pattern from a file in Python?

從包含HTTP響應和HTML頁面內容的數據文件中,我想僅使用Python提取HTTP響應(和標頭)。

數據文件具有以下重復模式,響應和標頭始終與空行分隔,並始終以HTTP / 1.1開頭。 我想要的是從“HTTP / 1.1 200 OK”行提取文本到空行上方的行(粗體字的文本)。

HTTP / 1.1 200好的

服務器:nginx

日期:2019年5月23日星期四19:49:06 GMT

內容類型:text / html; 字符集= UTF-8

X-Crawler-Transfer-Encoding:chunked

[空行]

頁面內容......

[空行]

HTTP / 1.1 200好的

...

這是我到目前為止,不知道如何進行。 我不熟悉Python,無法弄清楚如何讀取幾行並在循環中跳過它們。

with open('data') as f:
    lines = f.readlines()
    for line in lines:
        firstWord = line.split(' ')[0]
        if firstWord == 'HTTP/1.1':
                  what to do next?

您可以添加一個標志(例如, read )來檢查您是否要閱讀:

responses=[]
resp=''
read=False
with open('data') as f:
    lines = f.readlines()
    for line in lines:
        firstWord = line.split(' ')[0]
        if firstWord == 'HTTP/1.1':
            resp=line
            read=True
        elif firstWord=='\n' and resp:
            responses.append(resp)
            resp=''
            read=False
        elif read:
            resp+=line
print(responses)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM