【问题标题】:Python3 requests always returning same requestPython3 请求总是返回相同的请求
【发布时间】:2021-06-29 19:41:12
【问题描述】:

我正在制作一个加密货币手表应用程序。我使用这个请求,但我总是接受相同的请求。

coin_list = ["bitcoin", "ethereum", "bittorrent", "xrp", "dogecoin"]

while(True):
    for coin in coin_list:
        print(BeautifulSoup.get_text(BeautifulSoup(requests.get('https://www.coindesk.com/price/'+coin).content, 'html.parser').find('div', {'class': 'price-large'}))[1:])

这个脚本返回给我:

36,331.66
2,219.07
0.002826
0.716486
0.266623
36,331.66
2,219.07
0.002826
0.716486
0.266623
36,331.66
2,219.07
0.002826
0.716486
0.266623
36,331.66
2,219.07
0.002826
0.716486
0.266623
36,331.66
2,219.07
0.002826
0.716486
0.266623
36,331.66
2,219.07
0.002826

这与缓存无关。我尝试使用标题。

【问题讨论】:

  • 那么,程序到底出了什么问题?对于列表中的每个硬币,您都会得到不同的响应。
  • 我对每枚硬币都有不同的反应,但每枚硬币本身都返回相同的值

标签: python python-3.x beautifulsoup python-requests


【解决方案1】:

嗯,你在做:

while(True):
    ...

这意味着你将永远循环coin_list,因为这个条件总是True

这是一个正在发生的事情的例子。 (为了便于阅读,我已经重构了你的代码):

while True:
    for coin in coin_list:
        soup = BeautifulSoup(
            requests.get("https://www.coindesk.com/price/" + coin).content, "html.parser"
        )
        print(soup.find("div", {"class": "price-large"}).text)

    # The following will run after entirely looping over `coin_list`, we are still in the `while` loop
    print("Finished looping over `coin_list`")
    print()
    

输出:

$36,294.89
$2,213.96
$0.002825
$0.721100
$0.267331
Finished looping over `coin_list`

$36,294.89
$2,213.96
$0.002825
$0.721100
$0.267331
Finished looping over `coin_list`
...
... And on forever

所以,要解决这个问题,只需删除 while 条件,然后循环 coin_list

import requests
from bs4 import BeautifulSoup


coin_list = ["bitcoin", "ethereum", "bittorrent", "xrp", "dogecoin"]

for coin in coin_list:
    soup = BeautifulSoup(
        requests.get("https://www.coindesk.com/price/" + coin).content,
        "html.parser",
    )
    print(soup.find("div", {"class": "price-large"}).text)

输出:

$36,294.89
$2,216.34
$0.002825
$0.721100
$0.267331

【讨论】:

  • 问题不是 while 循环问题是 requests.get() 总是返回具有相同值的相同响应我如何在 while 循环中获取实时值
  • 我正在尝试 MendelG 发布的代码,但我得到了不同的数字。也许我们在不同的时间运行这段代码得到了不同的数字。
  • @THEBildeiz 您目前的问题是什么?请编辑您的问题以提供Minimal, Reproducible Example
  • 我目前正在运行此代码,但 while True:for 循环周围,time.sleep(120)for 之后。我有时会得到不同的数字。
  • 好的,那是另一个问题。
猜你喜欢
  • 2012-07-16
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
相关资源
最近更新 更多