Skip to main content
 首页 » 编程设计

python之如何使用 URLExtract 读取网络日志文件使用 python 获取唯一的 URL

2024年11月24日9grandyang

初学者 Python.. 我有一个很大的日志文件

如何仅读取和获取日志文件 URL,我试图仅获取某些 URL,例如 (https, http, :443, :80) 由于一些日志文件索引不同,如何从不同的行中正确读取某些字段

如何获得唯一的 URL 结果?我尝试了唯一的 URL,但无法获得唯一的 URL

示例日志文件格式:

60.80.94.184    anonymous   Moz/2.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) Apple/65.1.90 (HTML, like Gecko) Version/12.0 Mobile/15E Safari/604.1 2012-06-22  03:43:51    -   60.80.17.54 8090    0   781 9843    SSL-tunnel  -   qs.rtoas.zp:80  Upstream    0   0x3 Allowed 
180.81.82.170   anonymous   iPad1,3/09.1.1 (16q0)   2012-06-24  04:53:57    -   90.80.97.54 8070    47  217 8440    http    GET http://init-p0.pu.apple.com/bag?v=9 Upstream    200 0x400   Allowed 
109.13.61.195   anonymous   clo/76.119 Network/95.0.3 Dain/1.2.0    2012-06-25  09:43:54    -   190.22.19.94    8220    0   517 5057    SSL-tunnel  -   eree-022.opt-2.icloud-content.com:443   Upstream    0   0x8 Allowed 
20.81.82.110    anonymous   iPad1,1/09.1.1 (46q5)   2012-06-27  14:53:57    -   40.10.27.54 8070    47  217 8440    http    GET https://qwe-pu.uoras.com/bag?v=19   Upstream    200 x00 Allowed 

代码:

from urlextract import URLExtract 
files = "WEB_000.w3c" 
with open(files, 'r', encoding='utf-8') as f: 
    for i in f: 
        lines = i.strip() 
        extractor = URLExtract() 
        urls = extractor.find_urls(lines, only_unique=True) 
        li = list(set()) 
        for wa in urls: 
            li.append(wa) 
        for se in li: 
            print(se) 

请您参考如下方法:

urlextract 将仅从 lines 变量中的文本中提取唯一的 URL。但是您将所有内容附加在一起,如果多行具有相同的 URL,您将多次使用它。

如果 URL 的顺序不是问题,而您只想让它们独一无二,那么试试这个:

from urlextract import URLExtract 
 
files = "WEB_000.w3c" 
extractor = URLExtract() 
urls_unique = set() 
with open(files, 'r', encoding='utf-8') as f: 
    for line in f: 
        urls = extractor.find_urls(lines, only_unique=True) 
        urls_unique |= set(urls) 
print(urls_unique)