import json
import re
import pandas as pd
import requests
def test(addr):
# 京東商品原文鏈接
url_ = "%s#crumb-wrap" % addr
# 請求頭設置參數
header_ = {
"USER-AGENT": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36"
}
resp = requests.get(url=url_, headers=header_)
# 請求回來的文本內容(格式:字符串)
text = resp.text
# print(text)
# 從文本中查找參數開始拼接新的請求
sku_id = re.findall("skuid: (\\d+),", text)
cat = re.findall("cat: \\[(.*?)\\],", text)
vender_id = re.findall("venderId:(\\d+),", text)
# 如果三個參數有且都存在的情況下
if sku_id and cat and vender_id:
# 拼接新的路由(該鏈接是從網頁中的請求中查找獲取)
url_01 = "https://c0.3.cn/stock?skuId={}&cat={}&venderId={}&area=19_1601_3637_0".format(
sku_id[0], cat[0], vender_id[0])
# 開始我的請求,記得加上請求頭
res = requests.get(url=url_01, headers=header_)
# 將請求文本的格式從字符串轉換成json
json_data = json.loads(res.text)
# 從json數據中找到我要的原價和現價信息
o_price = json_data.get("stock", "").get("jdPrice").get("m", "") # 原價
c_price = json_data.get("stock", "").get("jdPrice").get("p", "") # 現價
test = json_data.get("stock", "").get("freshEdi", "") # 現價
print(test)
o_price_list.append(o_price)
c_price_list.append(c_price)
return o_price_list, c_price_list
# 定價列表
o_price_list = []
# 售價列表
c_price_list = []
df1 = pd.read_excel("test.xlsx", encoding="unicode_escape")
print(df1)
data1 = df1.ix[:, ['地址']].values
for i in data1:
test(i[0])
print(o_price_list,c_price_list)
df1["定價"] = o_price_list
df1["京東價"] = c_price_list
df1.to_excel("test.xlsx", index=None)
# if __name__ == '__main__':
# test()
python text.py or run text.py