我對 python 回圈相當陌生,需要一些幫助。我在下面有一個網址串列。每個 URL 中的數字代表不同的產品 ID,對于每個產品 ID(1、2、3 等),腳本都會運行價格更新 api 呼叫。
www.random.com/product/1/offer
www.random.com/product/2/offer
www.random.com/product/3/offer
我需要能夠遍歷每個 URL 并為每個產品 ID (1,2,3) 執行相同的任務 - 目前我將其設定如下,但想知道如何將 for 回圈集成到其中。當我嘗試使用陣列 for 回圈時,腳本只會在呼叫 URL 時執行陣列內的整個值。下面是我的單個 URL 代碼。
URL = 'www.random.com/product/1/offer'
ua = UserAgent()
#print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
headers2 = {'Content-Type': 'application/json', 'charset': 'utf-8', 'Accept': 'application/json', 'Authorization': 'xxx'}
def main():
response = requests.get(URL, headers=header)
response_formatted = json.loads(response.content.decode('utf-8-sig').encode('utf-8'))
price1 = response_formatted[0]["salePrice"]
print(price1)
discount_by=0.10
new_discount_price= (price1-discount_by)
print(new_discount_price)
sku = response_formatted[0]["sku"]
所以基本上我希望'URL'變數等于一堆不同的URL,并為每個唯一的URL值回圈主呼叫。
uj5u.com熱心網友回復:
我是python和stackoverflow的新手,但我最近這樣做了,所以我想我可以幫助你!!
我在一個函式中做了所有的事情,我確定它不是最好的,但它確實有效。我所做的就是將我想要更改的所有值放在一個串列中。
在你的情況下:
id=[1,2,3]
然后在函式中添加ua和headers,用for回圈做一個回圈:
def main():
listid=[1,2,3]
for i in listid:
idlist=i
ua = UserAgent()
# print(ua.chrome)
header = {'User-Agent': str(ua.chrome)}
headers2 = {'Content-Type': 'application/json', 'charset': 'utf-8', 'Accept': 'application/json',
'Authorization': 'xxx'}
conn.request(f"GET", f"www.random.com/product/{idlist}/offer", headers=headers)
res = conn.getresponse()
data = res.read()
data_formatted = json.loads(data.content.decode('utf-8-sig').encode('utf-8'))
price1 = data_formatted[0]["salePrice"]
print(price1)
discount_by = 0.10
new_discount_price = (price1 - discount_by)
print(new_discount_price)
sku = data_formatted[0]["sku"]
我不知道它是否有效,但我相信如果它錯了有人會修復它,我希望我能幫助你!
uj5u.com熱心網友回復:
感謝阿德里安,我明白了。解決方案是:
def main():
listid=[1,2]
for i in listid:
idlist=i
URL=f'https://www.random.com/products/{idlist}/offers'
ua = UserAgent()
#print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
headers2 = {'Content-Type': 'application/json', 'charset': 'utf-8', 'Accept': 'application/json', 'Authorization': 'xxx'}
response = requests.get(URL, headers=header)
response_formatted = json.loads(response.content.decode('utf-8-sig').encode('utf-8'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/434440.html
