【发布时间】:2019-03-25 22:48:48
【问题描述】:
我使用以下简化代码在线抓取数据后创建了一个 JSON 文件:
for item in range(items_to_scrape)
az_text = []
for n in range(first_web_page, last_web_page):
reviews_html = requests.get(page_link)
tree = fromstring(reviews_html.text)
page_link = base_url + str(n)
review_text_tags = tree.xpath(xpath_1)
for r_text in review_text_tags:
review_text = r_text.text
az_text.append(review_text)
az_reviews = {}
az_reviews[item] = az_text
with open('data.json', 'w') as outfile:
json.dump(az_reviews , outfile)
可能有更好的方法来创建一个 JSON 文件,其中第一个键等于项目编号,第二个键等于该项目的评论列表,但是我目前卡在打开 JSON 文件以查看项目已被抓取。
JSON 文件的结构如下所示:
{
"asin": "0439785960",
"reviews": [
"Don’t miss this one!",
"Came in great condition, one of my favorites in the HP series!",
"Don’t know how these books are so good and I’ve never read them until now. Whether you’ve watched the movies or not, read these books"
]
}
似乎更接近解决方案的不成功尝试如下:
import json
from pprint import pprint
json_data = open('data.json', 'r').read()
json1_file = json.loads(json_data)
print(type(json1_file))
print(json1_file["asin"])
它返回一个字符串,该字符串完全复制了我在抓取过程中使用的 print() 函数的结果,以检查 JSON 文件的外观,但我无法使用 @987654326 访问 asins 或评论@ 或 json1_file["reviews"] 因为读取的文件是字符串而不是字典。
TypeError: string indices must be integers
使用json.load() 函数,我仍然可以打印正确的内容,但我无法弄清楚如何从 JSON 文件访问类字典对象以遍历键和值。
以下代码打印文件的内容,但在我尝试遍历键和值时引发错误 (AttributeError: '_io.TextIOWrapper' object has no attribute 'items'):
with open('data.json', 'r') as content:
print(json.load(content))
for key, value in content.items():
print(key, value)
上面的代码有什么问题,应该调整什么以将文件加载到字典中?
【问题讨论】:
-
“我已经尝试了很多方法”没有帮助。如果你不展示你的尝试,没有人能说出你犯了什么样的错误。
-
我已经用错误的尝试更新了问题,你能发现我犯了哪些错误吗?谢谢
-
你认为你所有的尝试都应该奏效吗?你认为有人应该分析他们每个人。选择一个你认为应该起作用的,然后试着找出它为什么不起作用。去谷歌上查询。然后问一个具体的问题,例如我希望这个函数做一件事(例如,因为规范是这样说的),但它做了另一件事。显示发生了什么错误。然后你会有一个有效的问题。另见how to ask 和how to create a minimal, complete and verifiable example
-
如果你有文件,你真的应该使用
json.load()
标签: python json parsing dictionary web-scraping