简体   繁体   English

通过Python中的键显示输出中的单个值

[英]Display a Single Value from the output through a key in Python

I wrote a python script that gets the content of a particular url using Bs and requests module: the code is as follows: 我编写了一个python脚本,该脚本使用Bs和requests模块获取特定url的内容:代码如下:

import requests
from bs4 import BeautifulSoup
import json

page = requests.get(" ")
res = page.text
def srs(res):
  repls = ('srs(', ''), ('});', '')
  s = res
  rep1 = reduce(lambda a, kv: a.replace(*kv), repls, s)
  rep2 = rep1.replace('[', '')
  print rep2
srs(res)

The code works fine and does what it is intended to, the output is as follows: 该代码可以正常工作并达到预期目的,输出如下:

{"term":"allbany","moresuggestions":517,"autoSuggestInstance":null,"suggestions":{"group":"CITY_GROUP","entities":{"geoId":"1000000000000000355","destinationId":"1508137","landmarkCityDestinationId":null,"type":"CITY","caption":"Albany, Albany County, United States of America","redirectPage":"DEFAULT_PAGE","latitude":42.650249,"longitude":-73.753578,"name":"Albany"},{"geoId":"1000000000006058117","destinatioId":"1503240","landmarkCityDestinationId":null,"type":"CITY","caption":"Albany, Georgia, United States of America","redirectPage":"DEFAULT_PAGE","latitude":31.57695,"longitude":-84.151199,"name":"Albany"},{"geoId":"1000000000006135421"}.....

However is there a way where I could call a single value through a particular key. 但是,有一种方法可以通过特定键调用单个值。
For Eg suppose print rep2['term'] should display 'allbany' or rep2['moresuggestions'] should display '517'.I tried converting the output to Json and then displaying but it gives the error "String Indices must be int" 例如,假设print rep2 ['term']应该显示'allbany'或rep2 ['moresuggestions']应该显示'517'。我尝试将输出转换为Json,然后显示,但显示错误“ String Indices must int”

You can do the following: 您可以执行以下操作:

  • Convert the output to json, assuming the value is rep2 (as in your question) 假设值是rep2 (如您的问题),将输出转换为json
  • Use json.loads to convert it to Python object -- rep2_parsed = json.loads(rep2) 使用json.loads将其转换为Python对象rep2_parsed = json.loads(rep2)
  • You'll be able to use expressions like rep2_parsed['term'] 您将可以使用rep2_parsed['term']类的表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM