【发布时间】:2019-03-02 15:28:25
【问题描述】:
我用 Python 构建了一个爬虫。当我放置一个静态 URL 时它可以工作,但我想使用 JSON 文件为每个 URL 循环创建一个。
此代码返回错误,KeyError。我在网上说这是因为它是一个对象而不是数组。我不知道如何解决这个问题。有人可以以正确的方式指出我,甚至可以查看代码吗?我放置了一些错误的屏幕截图,我查找 JSON 信息的方式以及 JSON 文件的结构方式。
JSON 结构:
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)
【问题讨论】:
-
for website in json_dict['url'][0]['loc']: -
您不应该将图像用于代码。您应该在问题中包含所有相关代码。
-
@Barmar 对不起,您的代码也给出了错误:for website in json_dict['url'][0]['loc']: KeyError: 'url
-
在您在屏幕截图中显示之前,JSON 文件中是否有任何内容?您可以将 JSON 作为纯文本而不是图像发布吗?
标签: python json python-3.x beautifulsoup screen-scraping