rt requests as reqimport time,random,winsound,sendmessage,numpy as npfrom datetime import datetime class CS(): def __init__(self): self.nowtime = datetime.now() self.goodsurl = 'https://buff.163.com/api/market/goods' self.pricehistoryurl = 'https://buff.163.com/api/market/goods/price_history/buff' self.my_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", "Cookie": "yourcookie",#你自己的cookie "Host": "buff.163.com", "Referer": "https://buff.163.com/market/?game=csgo", "X-Requested-With": "XMLHttpRequest
时间: 2025-04-06 13:03:48 浏览: 34
### 关于使用 Python `requests` 库和 BUFF API 抓取商品价格历史
要实现通过 Python 的 `requests` 库调用 BUFF 平台的 API 接口来抓取商品的价格历史记录,需遵循以下方法:
#### 1. 准备工作
在开始之前,需要确认已安装必要的依赖库。如果没有安装这些库,则可以通过 pip 安装它们:
```bash
pip install requests
```
#### 2. 调用 BUFF API 获取数据
BUFF 提供了官方 API 来访问平台上的数据。以下是具体的操作流程。
- 首先构建 HTTP 请求头以及 URL 参数。
- 使用 `requests.get()` 方法发送 GET 请求至目标 API 地址。
- 解析返回的 JSON 数据并提取所需字段。
下面是一个简单的代码示例用于演示如何利用 `requests` 库与 BUFF API 进行交互[^1]:
```python
import requests
def fetch_item_price_history(api_key, item_id):
"""
Fetches the price history of an item from BUFF using their official API.
:param api_key: Your personal API key provided by BUFF.
:param item_id: The unique identifier for the desired item on BUFF's platform.
:return: A dictionary containing historical pricing information or None if failed.
"""
base_url = "https://buff.163.com/api/market/price_trend"
headers = {
'Authorization': f'Bearer {api_key}',
# Ensure you have a valid token here; replace with your actual authorization method as needed.
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
params = {'game': 'csgo', 'id': item_id}
try:
response = requests.get(base_url, headers=headers, params=params)
if response.status_code == 200:
result_data = response.json()
if not result_data['code'] == 'OK':
print(f"Error fetching data: {result_data}")
return None
prices_over_time = result_data["data"]["trend"]
return prices_over_time
else:
print(f"Failed to retrieve data due to status code {response.status_code}.")
return None
except Exception as e:
print(f"An error occurred while making the request: {e}")
return None
if __name__ == "__main__":
my_api_key = "<Your_API_Key_Here>"
target_item_id = "<Target_Item_ID>"
price_histories = fetch_item_price_history(my_api_key, target_item_id)
if price_histories is not None:
print(price_histories[:10]) # Print first ten entries just as example output.
```
此段代码展示了如何定义函数去请求特定物品的历史价格趋势,并处理响应中的错误情况。
#### 3. 处理 GZIP 压缩 HTML 页面的情况
如果遇到某些情况下服务器端返回的是经过 Gzip 压缩的内容而非纯文本格式时,可采用如下方式对其进行解压操作[^2]:
```python
import gzip
from io import BytesIO
compressed_data = b'\x1f\x8b...' # Example compressed binary string received via network call above
buffered_compressed_stream = BytesIO(compressed_data)
gzip_file_object = gzip.GzipFile(fileobj=buffered_compressed_stream)
unzipped_html_content_as_string = gzip_file_object.read().decode('utf-8')
print(unzipped_html_content_as_string)
```
以上片段说明了怎样读取字节流形式下的压缩文件对象再将其转码成 UTF-8 字符串表示出来。
#### 4. 结合 SeleniumWire 自动化浏览器行为采集动态加载内容
当面对那些仅靠 RESTful APIs 或静态页面无法满足需求的时候,可以尝试引入像 SeleniumWire 工具模拟真实用户的浏览动作从而捕获更多隐藏起来的信息源[^3].
注意这里提到的方法只是作为补充手段,在实际应用过程中应优先考虑合法合规途径获取公开披露的数据集。
---
阅读全文
相关推荐
















