我发现了一个python html解析器,它为html源构建了一个类似dom的结构,它看起来很容易使用,而且非常快。我正在尝试为从http://codepad.org/recent检索最后10篇文章的codepad.org编写一个搜索器
EHP lib在https://github.com/iogf/ehp,我有下面的代码,它正在工作。
import requests
from ehp import Html
def catch_refs(data):
html = Html()
dom = html.feed(data)
return [ind.attr['href']
for ind in dom.find('a')
if 'view' in ind.text()]
def retrieve_source(refs, dir):
"""
Get the source code of the posts then save in a dir.
"""
pass
if __name__ == '__main__':
req = requests.get('http://codepad.org/recent')
refs = catch_refs(req.text)
retrieve_source(refs, '/tmp/')
print refs 它输出:
[u'http://codepad.org/aQGNiQ6t',
u'http://codepad.org/HMrG1q7t',
u'http://codepad.org/zGBMaKoZ', ...]正如所料,但我想不出如何下载这些文件的源代码。
发布于 2016-03-29 22:09:58
实际上你的retrieve_source(refs, dir)什么也不做。
所以你没有得到任何结果。
根据您的评论进行更新:
import os
def get_code_snippet(page):
dom = Html().feed(page)
# getting all <div class=='highlight'>
elements = [el for el in dom.find('div')
if el.attr['class'] == 'highlight']
return elements[1].text()
def retrieve_source(refs, dir):
for i, ref in enumerate(refs):
with open(os.path.join(dir, str(i) + '.html'), 'w') as r:
r.write(get_code_snippet(requests.get(ref).content))https://stackoverflow.com/questions/36286640
复制相似问题