【问题标题】:Troubles merging two json urls合并两个 json url 的麻烦
【发布时间】:2021-01-02 19:32:24
【问题描述】:

首先,我收到了这个错误。当我尝试跑步时 pip3 install --upgrade json 在尝试解决错误时,python 无法找到该模块。 我正在使用的代码段可以在错误下方找到,但是对于代码本身的进一步说明将不胜感激。

错误:

Traceback (most recent call last):
  File "Chicago_cp.py", line 18, in <module>
    StopWork_data      = json.load(BeautifulSoup(StopWork_response.data,'lxml'))
  File "/usr/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
TypeError: 'NoneType' object is not callable

脚本:

#!/usr/bin/python

import json
from bs4 import BeautifulSoup
import urllib3
http = urllib3.PoolManager()

# Define Merge
def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res

# Open the URL and the screen name
StopWork__url = "someJsonUrl"
Violation_url = "anotherJsonUrl"

StopWork_response  = http.request('GET', StopWork__url)
StopWork_data      = json.load(BeautifulSoup(StopWork_response.data,'lxml'))

Violation_response = http.request('GET', Violation_url)
Violation_data     = json.load(BeautifulSoup(Violation_response.data,'lxml'))

dict3 = Merge(StopWork_data,Violation_data)
print (dict1)

【问题讨论】:

    标签: python json url


    【解决方案1】:

    json.load 需要一个文件对象或其他带有read 方法的东西。 BeautifulSoup 对象没有方法 read。您可以向它询问任何属性,它会尝试查找具有该名称的子标签,即在这种情况下为 &lt;read&gt; 标签。当它找不到一个时,它会返回None,这会导致错误。 Here's a demo:

    import json
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup("<p>hi</p>", "html5lib")
    assert soup.read is None
    assert soup.blablabla is None
    
    assert json.loads is not None
    json.load(soup)
    

    输出:

    Traceback (most recent call last):
      File "main.py", line 8, in <module>
        json.load(soup)
      File "/usr/lib/python3.8/json/__init__.py", line 293, in load
        return loads(fp.read(),
    TypeError: 'NoneType' object is not callable
    

    如果 URL 返回 JSON,那么您根本不需要 BeautifulSoup,因为它用于解析 HTML 和 XML。只需使用json.loads(response.data)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2017-10-13
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多