使用 lxml 库的 xpath 语法抓取伯乐在线的 python 爬虫部分文章 http://python.jobbole.com/tag/爬虫/ , 将数据存储到 mongodb. 本文主要练习 xpath 语法的使用和存储 mongodb 数据库的方式.
关于 xpath 的使用可以参考这篇文章 xpath 全面总结 https://zhuanlan.zhihu.com/p/35355747
- import requests # 导入网页请求库
- from lxml import etree # 导入网页解析库
- from pymongo import MongoClient
- def start_requests(url):
- r = requests.get(url)
- return r.content
- def parse(text):
- html = etree.HTML(text)
- divs = html.xpath('//div[@id="archive"]//div[@class="post-meta"]')
- for div in divs:
- # 一个中间变量
- comment = div.xpath('./p/a[3]/text()')
- # 使用生成器返回字典
- yield {
- 'title': div.xpath('./p/a[1]/text()')[0],
- 'url': div.xpath('./p/a[1]/@href')[0],
- 'time': div.xpath('./p//text()')[2].strip('. \r\n'),
- 'type':div.xpath('./p/a[2]/text()')[0],
- 'typeurl':div.xpath('./p/a[2]/@href')[0],
- 'comment':comment[0] if comment else None,
- 'excerpt': div.xpath('./span[@class="excerpt"]/p/text()')[0]
- }
- def get_all(): # 抓取所有页面, 返回包含所有信息的生成器
- for i in range(1, 6): # 循环抓取所有页
- url = 'http://python.jobbole.com/tag/爬虫/page/{}/'.format(i)
- text = start_requests(url)
- yield from parse(text)
- def main():
- client = MongoClient() # 连接数据库
- db = client.bole # 创建名为 bole 的数据库
- boledb = db.bole # 在 bole 数据库中创建表
- for item in get_all():
- boledb.insert_one(item) # 插入文档
- client.close() # 断开连接
- if __name__ == '__main__':
- main()
存到数据库的结果如下
阅读上面代码需要下面的基础知识
1. 爬虫基本原理 https://zhuanlan.zhihu.com/p/35324806
2.mongodb 的安装和使用, 看这两篇文章
mongodb 安装配置及介绍 https://zhuanlan.zhihu.com/p/34560583
python 连接 mongodb https://zhuanlan.zhihu.com/p/34562052
3.xpath 语法
xpath 全面总结 https://zhuanlan.zhihu.com/p/35355747
4. 在爬虫中使用生成器
爬虫代码改进 (三) https://zhuanlan.zhihu.com/p/35326858
专栏信息
专栏主页: python 编程 https://zhuanlan.zhihu.com/python-programming
专栏目录: 目录 https://zhuanlan.zhihu.com/p/33896532?refer=python-programming
爬虫目录: 爬虫系列目录 https://zhuanlan.zhihu.com/p/35379237
版本说明: 软件及包版本说明 https://zhuanlan.zhihu.com/p/29663336
来源: https://juejin.im/entry/5acdf50ff265da23a142438d