首页 > 解决方案 > 如何使用 python 请求在 url 网页中使用循环

问题描述

我正在尝试从网页中提取信息,我想在 url 网页中运行循环。有什么帮助吗?

abc = f"https://www.myntra.com/flat-60-sale?f=Brand%3AArrow%2CArrow%20New%20York%2CArrow%20Sport%2CBlackberrys%2CColorPlus%2CCrocodile%2CIndian%20Terrain%2CMarks%20%26%20Spencer%2CPark%20Avenue%2CParx%2CV%20Dot%2CVan%20Heusen%2CVan%20Heusen%20Sport%3A%3ACategories%3AShirts%3A%3AGender%3Amen%2Cmen%20women%3A%3AOccasion%3AFormal%3A%3Asize_facet%3A44&p=3&sort=price_asc"
for p in range(2,5):
    d = abc.replace("&p=3", "&p={p}") 
    d1 = f"{d}"
    re = requests.get(d1)
    print(re.status_code)

标签: pythonfor-loop

解决方案


看起来你对 f 弦有一点误解。abc应该是这样的:

abc = "https://www.myntra.com/flat-60-sale?.......&p={}&sort=price_asc"

然后,您可以在 for 循环中设置 p 值,如下所示:

for p in range(2,5):
    d1 = abc.format(p)
    re = requests.get(d1)
    print(re.status_code)

404您现在应该获得三个200状态码,而不是接收三个状态码


推荐阅读