Python三期爬虫作业

【Python爬虫】统计各自简书作业完成情况

2017-08-23  本文已影响41人  小丰丰_72a2

再次强调爬虫的逻辑是:请求url-->接收返回的数据-->解析数据-->愉快地存储,这里对于自己最难的还是url的构造,用什么方法来请求。


# -*- coding: utf-8 -*-
import requests
from lxml import etree


# 爬取专题页:
def get_title(url):
    res = requests.get(url)
    res.encoding = "utf-8"
    html = res.text
    selector = etree.HTML(html)
    infos = selector.xpath('//ul[@class="note-list"]//div[@class="content"]//a[@class="title"]')
    for info in infos:
        title_url = 'http://www.jianshu.com' + info.xpath('@href')[0]
        title_text = info.xpath('text()')[0]
        get_title_source(title_url, title_text)

# 爬取文章页:
def get_title_source(title_url, title_text):
    new_url = title_url
    new_res = requests.get(new_url)
    new_res.encoding = "utf-8"
    new_html = new_res.text
    new_selector = etree.HTML(new_html)
    new_infos = new_selector.xpath('//div[@class="note"]//div[@class="article"]//div[@class="info"]//a')
    for new_info in new_infos:
        author_name = new_info.xpath('text()')[0]
        # print(author_name)
        b.append(author_name)
        
# 函数用于统计提交次数
def t_imes(b):
    mylist = b
    myset = set(mylist)
    for item in myset:
        print("%r 提交次数:%r" %(item, mylist.count(item)))

if __name__ == '__main__':
    b = [ ]
    base_url = 'http://www.jianshu.com/c/1b31f26b6af0?order_by=added_at&page=%s'
    for page in range(1, 17):
        url = base_url %str(page)
        # print('第 %r 页' % page)
        get_title(url)
    t_imes(b)

运行结果:

C:\ProgramData\Anaconda3\python.exe E:/python/pachong.py/jianshu2.py
'duduxuam' 提交次数:5
'吃货就怕做饿梦' 提交次数:2
'张毛毛的成长记录仪' 提交次数:1
'infinite昊昊' 提交次数:6
'高杆python' 提交次数:1
'Ubuay' 提交次数:11
'五虎谷的阿格' 提交次数:1
'周TinTin' 提交次数:2
'DoctorLDQ' 提交次数:14
'大龙8788' 提交次数:1
'David大巍' 提交次数:5
'五虎谷的阿格2' 提交次数:10
'杯陌庭' 提交次数:11
'与非门salome' 提交次数:6
'Ziii_fcc5' 提交次数:3
'汇斤' 提交次数:1
'神奇星期八' 提交次数:13
'奔跑的Kay' 提交次数:9
'67e66d2b8ba4' 提交次数:4
'小涌Smallyong' 提交次数:3
'小丰丰_72a2' 提交次数:8
'_孙小籽' 提交次数:6
'飞奔的红舞鞋' 提交次数:5
'欣然面对' 提交次数:5
'龍猫君' 提交次数:2
'游离态的边缘人' 提交次数:1
'向右奔跑' 提交次数:1
'老妖精2016' 提交次数:5
'iamtjm' 提交次数:4
'程程同学' 提交次数:4
'ulan' 提交次数:3
'汤哥' 提交次数:4

Process finished with exit code 0
上一篇 下一篇

猜你喜欢

热点阅读