利用Python获取某游戏网站热销商品并用pands进行Excel数据存储
因为要求,这个不知名的网站用S代替了。
有刚刚使用S的用户,不知道玩什么游戏怎么办?往往热销商品会使他们最合适的选择。
当然,某个第三方的网站上面的数据会更详细,什么游戏用户活跃度高,哪个区服游戏价格更便宜上面都会有。但是加上了一层Cloudflare的浏览器验证。
有人说用cloudscraper,但是cloudscraper对商用版的Cloudflare好像不管用(应该是吧,如果有大佬有更好的方法请及时指出,谢谢),之后会用其他的方法再试试。所以这边先按下不表,开始获取S的热销信息。
一、热销获取分析
点击进入热销商品页:
https://那个网站/search/?sort_by=_ASC&force_infinite=1&snr=1_7_7_globaltopsellers_7&filter=globaltopsellers&page=2&os=win
上面的链接,仅仅能获取第一页的数据。
通过开发者模式找到真正的内容获取链接是:
https://那个网站/search/results/?query&start=0&count=50&sort_by=_ASC&os=win&snr=1_7_7_globaltopsellers_7&filter=globaltopsellers&infinite=1
其中start对应了开始位置,对应了翻页。count对应了一次获取了多少数据。
get请求即可,上代码:
def getInfo(self):url = 'https://那个网站/search/results/?query&start=0&count=50&sort_by=_ASC&os=win&snr=1_7_7_globaltopsellers_7&filter=globaltopsellers&infinite=1'res = self.getRes(url,self.headers,'','','GET')#自己封装的请求方法res = res.json()['results_html']sel = Selector(text=res)nodes = sel.css('.search_result_row')for node in nodes:gamedata = {}gamedata['url'] = node.css('a::attr(href)').extract_first()#链接gamedata['name'] = node.css('a .search_name .title::text').extract_first()#游戏名gamedata['sales_date'] = node.css('a .search_released::text').extract_first()#发售日discount = node.css('.search_discount span::text').extract_first()#是否打折gamedata['discount'] = discount if discount else 'no discount'price = node.css('a .search_price::text').extract_first().strip()#价格discountPrice = node.css('.discounted::text').extract()#打折后的价格discountPrice = discountPrice[-1] if discountPrice else ''gamedata['price'] = discountPrice if discountPrice else price#最终价格print(gamedata)
二、pandas保存数据
2.1 构建pandas DataFrame对象
pandas存储Excel数据利用的是pandas对象的to_excel方法,将pandas的Dataframe对象直接插入Excel表中。
而DataFrame表示的是矩阵的数据表,包含已排序的列集合。
首先,先将获取到的数据,构建成Dataframe对象,先将我们获取的数据分别存入对应的list中,获取的url存到url的list,游戏名存到name的list:
url = []name = []sales_date = []discount = []price = []
url = node.css('a::attr(href)').extract_first()
if url not in self.url:self.url.append(url)name = node.css('a .search_name .title::text').extract_first()sales_date = node.css('a .search_released::text').extract_first()discount = node.css('.search_discount span::text').extract_first()discount = discount if discount else 'no discount'price = node.css('a .search_price::text').extract_first().strip()discountPrice = node.css('.discounted::text').extract()discountPrice = discountPrice[-1] if discountPrice else ''price = discountPrice if discountPrice else priceself.name.append(name)self.sales_date.append(sales_date)self.discount.append(discount)self.price.append(price)
else:print('已存在')
将list组成相应的字典
data = {'URL':self.url,'游戏名':self.name,'发售日':self.sales_date,'是否打折':self.discount,'价格':self.price}
其中dict中的key值对应的是Excel的列名。之后用pandas的DataFrame()方法构建对象,之后插入Excel文件。
data = {'URL':self.url,'游戏名':self.name,'发售日':self.sales_date,'是否打折':self.discount,'价格':self.price}
frame = pd.DataFrame(data)
xlsxFrame = pd.read_excel('./steam.xlsx')
其中pd是引入pandas包的对象,约定俗成的见到pd就是引入了pandas。
import pandas as pd
2.2 pandas追加插入Excel
如果要是翻页的话,重复调用插入Excel方法时你会发现Excel表内的数据并不会增多,因为每一次to_excel()方法都会把你上一次写入的数据覆盖掉。
所以若想保留之前写入的数据,那就先把之前写入的数据读出来,然后和新产生的数据进行DaraFrame对象的合并,将总的数据再次写入Excel
frame = frame.append(xlsxFrame)
写入方法如下:
def insert_info(self):data = {'URL':self.url,'游戏名':self.name,'发售日':self.sales_date,'是否打折':self.discount,'价格':self.price}frame = pd.DataFrame(data)xlsxFrame = pd.read_excel('./steam.xlsx')print(xlsxFrame)if xlsxFrame is not None:print('追加')frame = frame.append(xlsxFrame)frame.to_excel('./steam.xlsx', index=False)else:frame.to_excel('./steam.xlsx', index=False)
逻辑:
- 将已有的数据生成DataFrame
- 读取之前写入的Excel文件,判断是否写入过数据
- 如果写入,将数据读出来合并后再次写入Excel
- 如果源文件为空,直接写入即可
三、代码整合
import requests
from scrapy import Selector
import pandas as pdclass getSteamInfo():headers = {"Host": "那个网站","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9","accept-encoding": "gzip, deflate, br","accept-language": "zh-CN,zh;q=0.9","user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",}url = []name = []sales_date = []discount = []price = []# api获取ipdef getApiIp(self):# 获取且仅获取一个ipapi_url = 'api地址'res = requests.get(api_url, timeout=5)try:if res.status_code == 200:api_data = res.json()['data'][0]proxies = {'http': 'http://{}:{}'.format(api_data['ip'], api_data['port']),'https': 'http://{}:{}'.format(api_data['ip'], api_data['port']),}print(proxies)return proxieselse:print('获取失败')except:print('获取失败')def getInfo(self):url = 'https://那个网站/search/results/?query&start=0&count=50&sort_by=_ASC&os=win&snr=1_7_7_globaltopsellers_7&filter=globaltopsellers&infinite=1'res = self.getRes(url,self.headers,'','','GET')#自己封装的请求方法res = res.json()['results_html']sel = Selector(text=res)nodes = sel.css('.search_result_row')for node in nodes:url = node.css('a::attr(href)').extract_first()if url not in self.url:self.url.append(url)name = node.css('a .search_name .title::text').extract_first()sales_date = node.css('a .search_released::text').extract_first()discount = node.css('.search_discount span::text').extract_first()discount = discount if discount else 'no discount'price = node.css('a .search_price::text').extract_first().strip()discountPrice = node.css('.discounted::text').extract()discountPrice = discountPrice[-1] if discountPrice else ''price = discountPrice if discountPrice else priceself.name.append(name)self.sales_date.append(sales_date)self.discount.append(discount)self.price.append(price)else:print('已存在')# self.insert_info()def insert_info(self):data = {'URL':self.url,'游戏名':self.name,'发售日':self.sales_date,'是否打折':self.discount,'价格':self.price}frame = pd.DataFrame(data)xlsxFrame = pd.read_excel('./steam.xlsx')print(xlsxFrame)if xlsxFrame is not None:print('追加')frame = frame.append(xlsxFrame)frame.to_excel('./steam.xlsx', index=False)else:frame.to_excel('./steam.xlsx', index=False)# 专门发送请求的方法,代理请求三次,三次失败返回错误def getRes(self,url, headers, proxies, post_data, method):if proxies:for i in range(3):try:# 传代理的post请求if method == 'POST':res = requests.post(url, headers=headers, data=post_data, proxies=proxies)# 传代理的get请求else:res = requests.get(url, headers=headers, proxies=proxies)if res:return resexcept:print(f'第{i+1}次请求出错')else:return Noneelse:for i in range(3):proxies = self.getApiIp()try:# 请求代理的post请求if method == 'POST':res = requests.post(url, headers=headers, data=post_data, proxies=proxies)# 请求代理的get请求else:res = requests.get(url, headers=headers, proxies=proxies)if res:return resexcept:print(f"第{i+1}次请求出错")else:return Noneif __name__ == '__main__':getSteamInfo().getInfo()
对了,本次数据是获取的美服数据哦。最近国内访问不稳定,若是想要获取数据不买游戏的话建议使用代理进行访问。我这里使用的时ipidea的代理,新用户可以白嫖流量哦。
地址:http://www.ipidea.net/?utm-source=csdn&utm-keyword=?wb
最后奉劝大家:适当游戏,理智消费 ,认真生活,支持正版。(大批量的数据还是存数据库吧,人家也支持导出Excel)
利用Python获取某游戏网站热销商品并用pands进行Excel数据存储相关推荐
- 可转债代码交流第二期:利用Python获取集思录数据(改)
上期内容讲解了宁稳网数据获取的方法(用于初步计算未上市可转债价格),具体方法参考第一期:可转债代码交流第一期:利用Python获取宁稳网数据(包含基本的环境搭建与Python编辑器安装方法) 本人并非 ...
- 利用 Python 获取余额宝历史收益数据
最近想做一个关于用一些指数基金与余额宝组成的简单 风险-无风险 投资组合的实验计算,发现通达信之类的行情软件并没有提供完整的余额宝收益信息,如通达信仅有年化收益率的数据,并没有万份收益的数据.因此考虑 ...
- 在Linux上利用python获取本机ip
下面介绍在Linux上利用python获取本机ip的方法. 经过网上调查, 发现大致有两种方法, 一种是调用shell脚本,另一种是利用python中的socket等模块来得到,下面是这两种方法的源码 ...
- python过去日期_利用python获取当前日期前后N天或N月日期的方法示例
前言 最近因为工作原因,发现一个Python的时间组件,很好用分享出来!(忘记作者名字了,在这里先感谢了),下面话不多说,来一起看看详细的介绍吧. 示例代码: # -*- coding: utf-8 ...
- Python语言学习:利用python获取当前/上级/上上级目录路径(获取路径下的最后叶目录的文件名、合并两个不同路径下图片文件名等目录/路径案例、正确加载图片路径)之详细攻略
Python语言学习:利用python获取当前/上级/上上级目录路径(获取路径下的最后叶目录的文件名.合并两个不同路径下图片文件名等目录/路径案例.正确加载图片路径)之详细攻略 目录 利用python ...
- python自动保存ping结果_利用python获取Ping结果示例代码
前言 本文主要跟大家分享了关于利用python获取Ping结果的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍吧. 示例代码: # -*- coding: utf-8 -*- i ...
- windows和Linux利用Python快速搭建一个网站
windows和Linux利用Python快速搭建一个网站 一.windows 步骤1:安装Python3(自行百度) 步骤2:在cmd窗口输入ipconfig查看本机ip地址,IPV4那一行.如:1 ...
- python读取sas数据集_利用Python获取SAS和R自带数据集
图:北京-奥森公园-2018年4月 无论是SAS.R还是Python,本身都自带一些数据集,对于初学者来说,可以通过这些自带的小数据集进行编程练习,无疑是非常方便的.SAS.R作为统计分析软件,本身自 ...
- 实战教程!利用Python获取数据,并在地图上批量标注
我们想要在地图上批量标注某一类的大量点位,该怎么操作呢?没有它的坐标数据,就没有办法批量标注.今天给大家介绍下,来自图新地球用户王泽的原创教程--利用Python获取数据,并在地图上批量标注的方法! ...
最新文章
- 基于多视图几何方式的三维重建
- Android 抓取app进程 hprof 文件
- Leetcode 209. 长度最小的子数组 解题思路及C++实现
- Framebuffer 机制
- 一款非常好用的Linux下的C/C++ IDE
- GDCM:读取PatientName的测试程序
- SAP UI5 应用开发教程之三十 - SAP UI5 的路由过程中进行参数传递试读版
- 小学教师计算机国培培训总结,小学教师国培培训心得体会
- JavaScript学习(三十一)—在输入框中如何判断输入的是一个正确的网址
- 有安全研究者混入了 PHP 8.0 开发组!
- 谁在让字节跳动?张一鸣领衔14大将,106位高管架构首次曝光
- 轻量通用型互联网应用架构
- Sublime Text3插件管理
- HZAU毕设之装订边边距32 mm、非装订边边距25 mm的操作
- 《windows》win10禁用默认输入法
- Flutter 实现切角渐变矩形
- svm和k-最近邻_使用K最近邻的电影推荐和评级预测
- 苹果闭门造车6年了!是否已经“翻车”?
- 基于JAVAEE的洗衣店费用管理系统
- Geography和 Geometry 的区别