使用Python爬虫代码获取数据到Power Query中

通过前面的几篇文章Power BI Python 在Power BI Desktop中使用Python导入数据Power BI Python 在Power BI Desktop中Python代码如何使用Power Query数据,我们简单的了解了如何在Power BI运行Python代码,那么今天我们就用一个实际的Python爬虫代码来跑下。

 

本示例的代码目的是将我的博客园所有的帖子的基本信息都爬取下来,包括发布日期、发布时间、标题、阅读量以及评论数都提取出来。

import requests
from lxml import etree
import pandas as pd

base_url="https://www.cnblogs.com/alexywt/default.html?page="
articles=pd.DataFrame(columns=('day','title','desc'))

def getArticles(startId,endId):
    for i in range(startId,endId):
        getArticlesFromPage(i)


def getArticlesFromPage(pageId):
    global articles

    url=base_url+str(pageId)

    resp=requests.get(url)
    html=etree.HTML(resp.text)
    days= html.xpath('//div[@class="day"]')
    for day in days:
        article=getArticle(day)
        if not article is None:
            articles=articles.append(article,ignore_index=True)


def getArticle(div_day):
    article_title=div_day.xpath('.//div[@class="postTitle"]/a/text()')[0]
    article_title=article_title.replace("\n","")
    if article_title[:4]=="[置顶]":
        return None

    article_title=article_title.strip()
    day_title=div_day.xpath('.//div[@class="dayTitle"]/a/text()')[0]
    post_desc=div_day.xpath('.//div[@class="postDesc"]/text()')[0]
    post_desc=post_desc.replace("\n","")

    article=pd.Series({
        'day': day_title,
        'title': article_title,
        'desc': post_desc.strip()
    })

    return article



if __name__=='__main__':
    getArticles(1,7)
    print(articles)

代码简单说明:

1、首先定义了基地址以及一个最终用于存储所有数据的DataFrame对象

2、随后定义了3个函数,这三个函数的功能如下所示

函数名 参数 功能
getArticles
startId:起始页的页码
endId:结束页的页码
获取从起始页到结束页中所有的文章信息
getArticlesFromPage
pageId:当前页的页码
获取指定页中所有文章的信息,并且清除掉置顶文章
getArticle
div_day:当前文章所在的div元素
从当前文章所在的div元素中提取文章的信息,并存入一个Series对象中

 

在Power BI中运行以上Python代码后,导入的结果如下图所示

image

 

通过Power Query的一些变换操作将结果转变为如下结果

image

 

最后通过Power BI的Power View设计几个图表,我这里比较随意的配置了几种

image

 

注意:Power BI集成Python代码后,后续如果有新博客文章发布,或者阅读量增加时,只需要打开Power BI文件,刷新一下预览即可得到新的结果

posted @ 2019-08-26 15:58  alexywt  阅读(2203)  评论(0编辑  收藏  举报