网络爬虫-第一次实现
之前总觉得网络爬虫非常奇妙,这次终于有机会实现一下。
代码已经上传到github中。
先总结一下心得:
1、python里json包对于字典、列表等数据结构输出非常友好,配套的函数有:
a) json.dumps(data, indent=1, ensure_ascii=False) // 返回值为string类型字符串,可以直接print,或者f.write()到文件
b) json.loads(....) // 没有使用到
1 def output_dict(file, data): 2 with open(file, "w", encoding="utf-8") as f: 3 jsonDumpsIndentStr = json.dumps(data, ensure_ascii=False, indent=1) 4 f.write(jsonDumpsIndentStr) 5 return 6 7 def output_table(file, table): 8 with open(file, "w", encoding="utf-8") as f: 9 jsonDumpsIndentStr = json.dumps(list(table), indent=1, ensure_ascii=False) 10 f.write(jsonDumpsIndentStr) 11 return
2、beautifulsoup4包 基本可以实现对html代码的所有操作,这次只是简单的试了几个,还没有系统的了解,但已经可以感受出它的强大了。
通过使用beautifulsoup函数,可以将html代码转化成文档树(文档树),从而实现对元素的遍历、查找等操作。
常见的类型有bs4.element.Tag和bs4.element.NavigableString等,前者是一个字典,后者是字符串。
3、网络爬虫可以分为四个模块:下载器,URL管理器,解析器,爬虫管理器。
4、在爬取百度百科html代码中<table>类型的数据时,非常苦恼该怎么提取和存储。在看到这篇文章(https://stackoverflow.com/questions/18544634/convert-a-html-table-to-json)时才恍然大悟,代码真奇妙。
为了防止链接失效等意外情况发生,将原文截图如下:




浙公网安备 33010602011771号