【问题标题】:Using Python for web scraping: TypeError: argument of type 'NoneType' is not iterable使用 Python 进行网页抓取:TypeError:“NoneType”类型的参数不可迭代
【发布时间】:2019-11-30 08:28:51
【问题描述】:
import urllib.request, urllib.parse, urllib.error
import json

serviceurl = "http://python-data.dr-chuck.net/geojson?"

while True:

address = "Farmingdale State University"
if len(address) < 1 : 
    break

url = serviceurl + urllib.parse.urlencode({'sensor':'false','address':address})

print ('Retrieving',url)


uh =urllib.request.urlopen(url)
data = uh.read()
print ('Retrived',len(data),'characters')

try: (js) = json.loads(str(data))
except: (js) = None
if ('status' not in js) or (js['status'] != 'OK'):
    print ('==== Failure To Retrieve ====')
    print (data)
    continue

placeid = js["results"][0]['place_id']
print ("Place id",placeid)

文件“”,第 23 行,在 if ('status' not in js) or (js['status'] != 'OK'):

TypeError: 'NoneType' 类型的参数不可迭代

【问题讨论】:

  • 如果 js 为 none,则无法对其进行迭代。 None 中的“状态”是不可能的

标签: python json web-scraping


【解决方案1】:

如果 js 是 None 那么你会得到这个错误。尝试检查 js 是否为 True,然后再进一步检查其内容。

现在,当您的代码失败时,try 块并转到 except js 将设置为 None ,然后仍然检查 if 语句。

【讨论】:

    【解决方案2】:
    • json.loads() - 从代表 json 对象的字符串中返回一个对象。

    例如

    import urllib.request, urllib.parse, urllib.error
    import json
    
    serviceurl = "http://python-data.dr-chuck.net/geojson?"
    address = "Farmingdale State University"
    url = serviceurl + urllib.parse.urlencode({'sensor':'false','address':address})
    
    while True:
        uh =urllib.request.urlopen(url)
        response = uh.read()
        data = json.loads(response)
        if 'status' in data and data['status'] != 'OK':
            continue
        #check place_id is exists in dictionary
        if 'results' in data and len(data['results']) > 0 and 'place_id' in data['results'][0]:
            print(data["results"][0]['place_id'])
            break
    

    O/P:

    ChIJScDUqFcq6IkRpvubNFOAVmw
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多