如何从JSON中检索信息?

时间:2018-09-26 19:18:45

标签: python json python-3.x beautifulsoup screen-scraping

我用Python构建了一个scraper。当我放置一个静态URL时它可以工作,但是我想为每个URL循环都使用JSON文件。

此代码返回错误KeyError。我在线上表示发生这种情况是因为它是对象而不是数组。我不确定如何解决此问题。有人可以用正确的方式指出我,甚至可以检查代码吗?我放了一些错误的屏幕截图,查找JSON信息的方式以及JSON文件的结构。

JSON结构:

enter image description here

from bs4 import BeautifulSoup
import requests
import json

with open("C:\data.json") as my_json:
    json_dict = json.load(my_json)
for website in json_dict[0][0]:
    print("About to scrape: ", website)


print('step 1')
#get url
page_link = website
print('step 2')
#open page
page_response = requests.get(page_link, timeout=1)
print('step 3')
#parse page
page_content = BeautifulSoup(page_response.content, "html.parser")
print('step 4')
#Find info
naam = page_content.find_all(class_='<random class>')[0].decode_contents()
print('step 5')
#Print
print(naam)

1 个答案:

答案 0 :(得分:-1)

在您的json文件中,整个内容的左括号未命名,请尝试为其命名数据,然后使用json_dict['data']['url']['loc'][0]进行调用(对于URL本身)