使用Python爬虫代码获取数据到Power Query中
发布时间:2020-12-20 10:52:18 所属栏目:Python 来源:网络整理
导读:通过前面的几篇文章 Power BI Python 在Power BI Desktop中使用Python导入数据 、 Power BI Python 在Power BI Desktop中Python代码如何使用Power Query数据 ,我们简单的了解了如何在Power BI运行Python代码,那么今天我们就用一个实际的Python爬虫代码来跑
通过前面的几篇文章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 article != 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个函数,这三个函数的功能如下所示
? 在Power BI中运行以上Python代码后,导入的结果如下图所示 ? 通过Power Query的一些变换操作将结果转变为如下结果 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |