【问题标题】:why is Json parsing breaking While loop?为什么 Json 解析会破坏 While 循环?
【发布时间】:2020-10-04 07:37:12
【问题描述】:

我正在尝试创建一个程序,只要以太坊价格发生相当大的变化,它就会给我发短信。为了做到这一点,我有一个 while 循环不断地解析和获取信息。但是它会给我三遍信息,然后给我错误:

change = json.loads(soup.select_one('script#server-app-state').contents[0])
AttributeError: 'NoneType' object has no attribute 'contents'

我的代码:

import json
import time
import requests
from bs4 import BeautifulSoup
normalprice = True
URL = 'https://www.coinbase.com/price/ethereum'

while normalprice:
    soup = BeautifulSoup(requests.get(URL).content, "html.parser")
    change = json.loads(soup.select_one('script#server-app-state').contents[0]) 
    BDP = change['initialData']['data']['prices']['prices']['latestPrice']['percentChange']['day']
    BRV = round(BDP * 100, 2)
    print (BRV,'%')

【问题讨论】:

  • 因为当时select_one('script#server-app-state') 返回了None,并且在None 上调用.contents 引发了异常。

标签: python json parsing beautifulsoup


【解决方案1】:

您收到“CAPTCHA”页面是因为您太快地发出了太多请求。将time.sleep() 放入循环中,将try..except 放在json.loads 周围。

例如:

import json
import time
import requests
from bs4 import BeautifulSoup


normalprice = True
URL = 'https://www.coinbase.com/price/ethereum'

while normalprice:
    time.sleep(3)
    soup = BeautifulSoup(requests.get(URL).content, "html.parser")
    try:
        change = json.loads(soup.select_one('script#server-app-state').contents[0])
    except:
        print('-')
        continue
    BDP = change['initialData']['data']['prices']['prices']['latestPrice']['percentChange']['day']
    BRV = round(BDP * 100, 2)
    print (BRV,'%')

打印:

-2.21 %
-2.21 %
-2.21 %
-
-
-
-
-2.21 %
-2.21 %
-2.21 %
-

... and so on.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 2016-08-17
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多