I have been trying to get this list of variables to work but it keeps giving me keyerror I have tried changing the variable etc but wont work
#client.command()
async def info(ctx):
url = ('https://randomuser.me/api/')
response = requests.get(url)
title = response.json()["title"]
first = response.json()["first"]
last = response.json()["last"]
number = response.json()["number"]
street = response.json()["name"]
city = response.json()["city"]
state = response.json()["state"]
postcode = response.json()["postcode"]
country = response.json()["country"]
phone = response.json()["phone"]
age = response.json()["age"]
dob = response.json()["date"]
gender = response.json()["gender"]
username = response.json()["username"]
password = response.json()["password"]
image = response.json()["large"]
embed = discord.Embed(title="Fake Info Generator", description=f"**Name:** '{title}', '{first}' '{last}'\n**Address:** '{number}' '{street}', '{city}', '{state}', '{postcode}', '{country}'\n**Phone:** '{phone}'\n**Age:** '{age}', '{dob}'\n**Gender:** '{gender}'", color=18321)
embed.set_footer(text="Random Info")
embed.set_image(url=f"'{image}'")
await ctx.send(embed=embed)
I have tried things like changing the variables to thing like this but still wont work
title = response.json()["name"][0]["title"]
Simply because that's now how JSON reading works.
You need to specify the entire "path" of the value you want to read. You can't just get response.json()["title"] because the response is not formatted like that.
The response JSON is formatted like the following:
{
"results":[
{
"gender":"female",
"name":{
"title":"Madame",
"first":"Germaine",
"last":"Rey"
},
...
}
],
...
}
To be able to read title you would need to read the content of the array results at index 0 (because you only care of the first result) then check the name and then finally the title, so it would look like that: response.json()["results"][0]["name"]["title"]
Related
I have an excel file, which contains only one sheet, called 'Sheet1'. What I want to do is read all the rows from each column to send that data to a request in an API. I'm only able to send the last data of the worksheet, using this code:
my_table = pd.read_excel("Myexcel.xlsx")
for i, name in enumerate(my_table["Name"]):
categ = str(int(my_table.loc[i, "CategoryId"]))
brd = my_table.loc[i, "BrandName"]
des = my_table.loc[i, "Description"]
titl = my_table.loc[i, "Title"]
payloads = {"Name": name, "CategoryId": categ, "BrandName": brd, "Description": des, "Title": titl}
response = requests.post(url, headers=headers, json=payloads)
response = response.json()
What I want to do is send all the values. I couldn't specify how many lines there are, because the amount of data in the file can be changed, either more or less. I would like to do this in python
It looks to me like you are assigning name, Category.id .... Title to values associated with rows, and then not doing anything with them before reassigning the values again.
if the comments I'm reading [here] are to be believed, it seems you can make the elements of your payload lists, where the elements in the list are elements from your row/xlsx file.
Maybe try something like
my_table = pd.read_excel("Myexcel.xlsx")
for i, name in enumerate(my_table["Name"]):
categ.append(str(int(my_table.loc[i, "CategoryId"])))
brd.append(my_table.loc[i, "BrandName"])
des.append(my_table.loc[i, "Description"])
titl.append(my_table.loc[i, "Title"])
payloads = {"Name": name, "CategoryId": categ, "BrandName": brd, "Description": des, "Title": titl}
response = requests.post(url, headers=headers, json=payloads)
response = response.json()
Can't promise anything though, sorry! This is the route I would try, but I don't know if it will lead anywhere. I'm going to post another link that may contain helpful discussion here
I am new to python and currently learning this language. I am trying to build a web scraper that will export the data to a CSV. I have the data I want and downloaded it to a CSV. The problem is that I have only managed to dump the data from one index and I want to dump all the data from all the indexes into the same CSV to form a database.
The problem I have is that I can only request n_companies indicating the index. For example (n_company[0] ) and I get the data from the first index of the list. What I want is to get all the data from all the indexes in the same function and then dump them with pandas in a CSV and thus be able to create a DB.
I'm stuck at this point and don't know how to proceed. Can you help me please.
This is the function:
def datos_directorio(n_empresa):
r = session.get(n_empresa[0])
home=r.content.decode('UTF-8')
tree=html.fromstring(home)
descripcion_direccion_empresas = '//p[#class = "paragraph"][2]//text()[normalize-space()]'
nombre_e = '//h1[#class ="mb3 h0 bold"][normalize-space()]/text()'
email = '//div[#class = "inline-block mb1 mr1"][3]/a[#class = "mail button button-inverted h4"]/text()[normalize-space()]'
teléfono = '//div[#class = "inline-block mb1 mr1"][2]/a[#class = "tel button button-inverted h4"]/text()[normalize-space()]'
d_empresas=tree.xpath(descripcion_direccion_empresas)
d_empresas = " ".join(d_empresas)
empresas_n=tree.xpath(nombre_e)
empresas_n = " ".join(empresas_n[0].split())
email_e=tree.xpath(email)
email_e = " ".join(email_e[0].split())
teléfono_e=tree.xpath(teléfono)
teléfono_e = " ".join(teléfono_e[0].split())
contenido = {
'EMPRESA' : empresas_n,
'EMAIL' : email_e,
'TELÉFONO' : teléfono_e,
'CONTACTO Y DIRECCIÓN' : d_empresas
}
return contenido
Best regards.
Hello so I have been trying to fox this for a few hours now and just cant figure out what is wrong, I have made api calls in discord python before but this is the first time using multiple variables like this.
#client.command()
async def random(ctx):
url = ('https://randomuser.me/api/')
response = requests.get(url)
title = response.json()["title"]
first = response.json()["first"]
last = response.json()["last"]
number = response.json()["number"]
street = response.json()["name"]
city = response.json()["city"]
state = response.json()["state"]
postcode = response.json()["postcode"]
country = response.json()["country"]
phone = response.json()["phone"]
age = response.json()["age"]
dob = response.json()["date"]
gender = response.json()["gender"]
username = response.json()["username"]
password = response.json()["password"]
image = response.json()['large']
embed = discord.Embed(title="Random Generator", description="**Name:** f'{title}, {first} {last}\n**Address:** {number} {street}, {city}, {state}, {postcode}, {country}\n**Phone:** {phone}\n**Age:** {age}, {dob}\n**Gender:** {gender}\n**Alias:** {username}, {password}\n\n**Profile Picture Link:** {large}'", color=18321)
embed.set_footer(text="Thanks for using the bot")
embed.set_image(url="value=f'{large}'")
await ctx.send(embed=embed)
Please if anyone knows what is wrong and can help thank you
f-strings cannot be used inside other strings.
Instead of doing
description="**Name:** f'..."
you should do
description=f"**Name:** {title}..."
Same with all your f-strings
You can't use f-strings inside other strings like "name: f'{title}'". Try this instead:
description = f"**Name:** {title}..."
def location():
res = requests.get('https://ipinfo.io/')
data = res.json()
stad = data['city']
location = data['loc'].split('.')
latitude = location[0]
longitude = location[1]
return stad
def get_weather():
location(stad)
weather_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
url = 'https://api.openweathermap.org/data/2.5/weather'
# q=Amsterdam&appid=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
city = location(stad)
params = {'q': city, 'APPID': weather_key, 'units': 'metric'}
response = requests.get(url, params= params)
print(f'Het weer vandaag in Utrecht is:')
print(response.json())
Dear stackoverflow users,
I try to get my from city = location(stad) from def location() ((stad means city in dutch))
but it doesnt work python says location(stad) is not defined what can i do to fix this issue?
You mishandled the function response. Instead of assigning the response into a variable, you have passed a parameter (Undefined variable) to the function "location".
Instead of location(stad), you have to use stad = location().
Also, there are few things I saw in your code which might be unnecessary -
In "location" definition, since you are returning only the city(stad), you do not have to process the longitude and latitude. Also, since longitude/latitudes can be in decimals, you may not get exact values if you split using "period"(.).
location(stad) is not defined, because "location" is a function that does not receive parameters.
You have to write:
city = location(), then the variable "stad" that calculated in the function "location" will assign to your var "city". Is it clear?
In addition, the line :
location(stad)
(at the beginning of the function get_weather() )
looks like unnecessary line. why to call the function, if you do not use what was returned?
Is a dictionary the correct way to be doing this? Ideally this will be more then 5+ deep. Sorry my only language experience is powershell there I would just make an array of object. Im not looking for someone to write the code I just wanna know if there is a better way?
Thanks
Cody
My Powershell way:
[$title1,$title2,$title3]
$titleX.comment = "comment here"
$titleX.comment.author = "bob"
$titleX.comment.author.karma = "200"
$titleX.comment.reply = "Hey Bob love your comment."
$titleX.comment.reply.author = "Alex"
$titleX.comment.reply.reply = "I disagree"
#
Python code Borken:
import praw
d = {}
reddit = praw.Reddit(client_id='XXXX',
client_secret='XXXX',
user_agent='android:com.example.myredditapp:'
'v1.2.3 (by /u/XXX)')
for submission in reddit.subreddit('redditdev').hot(limit=2):
d[submission.id] = {}
d[submission.id]['comment'] = {}
d[submission.id]['title']= {}
d[submission.id]['comment']['author']={}
d[submission.id]['title'] = submission.title
mySubmission = reddit.submission(id=submission.id)
mySubmission.comments.replace_more(limit=0)
for comment in mySubmission.comments.list():
d[submission.id]['comment'] = comment.body
d[submission.id]['comment']['author'] = comment.author.name
print(submission.title)
print(comment.body)
print(comment.author.name)
print(d)
File "C:/git/tensorflow/Reddit/pull.py", line 23, in <module>
d[submission.id]['comment']['author'] = comment.author.name
TypeError: 'str' object does not support item assignment
#
{'6xg24v': {'comment': 'Locking this version. Please comment on the [original post](https://www.reddit.com/r/changelog/comments/6xfyfg/an_update_on_the_state_of_the_redditreddit_and/)!', 'title': 'An update on the state of the reddit/reddit and reddit/reddit-mobile repositories'}}
I think your approach using a dictionary is okay, but you might also solve this by using a data structure for your posts: Instead of writing
d[submission.id] = {}
d[submission.id]['comment'] = {}
d[submission.id]['title']= {}
d[submission.id]['comment']['author']={}
d[submission.id]['title'] = submission.title
you could create a class Submission like this:
class Submission(object):
def __init__(self, id, author, title, content):
self.id = id
self.author = author
self.title = title
self.content = content
self.subSubmissions = {}
def addSubSubmission(self,submission):
self.subSubmission[submission,id] = submission
def getSubSubmission(self,id):
return self.subSubmission[id]
by using you could change your code to this
submissions = {}
for sm in reddit.subreddit('redditdev').hot(limit=2):
submissions[sm.id] = Submission(sm.id, sm.author, sm.title, sm.content)
# I am not quite sure what these lines are supposed to do, so you might be able to improve these, too
mySubmission = reddit.submission(id=sm.id)
mySubmission.comments.replace_more(limit=0)
for cmt in mySubmission.comments.list():
submissions[sm.id].addSubSubmission(Submission(cmt.id, cmt.title, cmt.author, cmt.body))
By using this apporach you are also able to export the code to readout the comments/subSubmissions into an extra function which can call itself recursively, so that you can read infitive depths of the comments.