python

Python第一个项目:爬取个人简书主页文章信息

2019-08-07  本文已影响78人  祈澈菇凉

前面两篇安装完成了爬虫所需要的环境和工具,也踩了几个坑之后,今天开始写代码,开始写python第一个项目,把自己的简书简书主页文章信息爬取下来。首先确保已经安装 requests和lxml模块,如果没有安装,可以使用命令安装。

目标链接:https://www.jianshu.com/u/05f416aefbe1

1:新建一个.py 文件写代码
在项目上右键,点击New,选择Python File

2:给file取个名字,点击回车确定。系统会默认生成first.py 文件


3:在first.py 文件写上以下代码

import requests
from lxml import etree
import os
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'}
for i in range(1,4):
    url_ = 'https://www.jianshu.com/u/05f416aefbe1?order_by=shared_at&page={}'.format(i)
    res = requests.get(url_,headers=headers)
    res = etree.HTML(res.content.decode())
    nodes = res.xpath('//ul[@class="note-list"]/li')
    for node in nodes:
        item = {}
        title = node.xpath('.//a[@class="title"]/text()')
        time = node.xpath('.//span[@class="time"]/@data-shared-at')[0]
        abstract = node.xpath('.//p[@class="abstract"]/text()')[0]
        img = node.xpath('.//img[@class="  img-blur-done"]')
        url = 'https://www.jianshu.com'+node.xpath('.//a/@href')[0]
        item['title'] = title
        item['time'] = time
        item['url'] = url
        item['abstract'] = title
        item['img'] = time
        print(item)

4:在文件上鼠标右键点击运行按钮。

5:在控制台上可以看到运行结果
爬取到了个人简书主页文章信息,也可以将这些json数据封装成接口,在要使用到的地方调用即可。


原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的程序媛一枚,欢迎关注【编程微刊】公众号,回复【领取资源】,500G编程学习资源干货免费送。

上一篇 下一篇

猜你喜欢

热点阅读