使解析简洁
parsechain的Python项目详细描述
一种能够流畅地、尽可能声明性地解析html的方法。这是在alpha阶段现在,情况将发生变化。
安装
pip install parsechain
用法
importrequestsfromparsechainimportC,Response# Fetch html and cast itresponse=Response.cast(requests.get(...))# Get a movie title and ratingtitle=response.css('h1 .title').textrating=response.css('.left-box').inner_text.re(r'IMDb: ([\d.]+)').float# Or bothmovie=response.root.multi({'title':C.css('h1 .title').text,'rating':C.css('.left-box').inner_text.re(r'IMDb: ([\d.]+)').float,})
最后一个示例可以扩展为显示链重用:
defby_label(label):returnC.css('.left-box').inner_text.re(fr'{label}: ([\w.]+)')parse_movie=C.multi({'title':C.css('h1 .title').text,'rating':by_label('IMDb').float,'status':by_label('Status').trim,})movie=parse_movie(response.root)# Pass a root of a tree
可用操作的完整列表可以在parsechain.chains.Ops类中看到。有朝一日,要遵循正确的文档;)