Python 3.3.2 - trying to read url from wunderground - python

I have been struggling for a while trying to convert some code from an older version of Python. I'm simply trying to run an api lookup from wunderground and I can't get past my errors in python. Here is the error:
f = urllib.request.urlopen(fileName)
AttributeError: 'module' object has no attribute 'request'
The code is pretty straight forward, I know i"m missing something simple, thanks for any help.
import urllib
import json
key = "xxxxxxxxxxxxxxxxx"
zip = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip + ".json"
f = urllib.request.urlopen(fileName)
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print ("Current temperature in %s is: %s % (location, temp_f)")
close()

Sometimes importing a package (e.g. numpy) automatically imports submodules (e.g. numpy.linalg) into its namespace. But that is not the case for urllib. So you need to use
import urllib.request
instead of
import urllib
in order to access the urllib.request module. Alternatively, you could use
import urllib.request as request
in order to access the module as request.
Looking at the examples in the docs is a good way to avoid problems like this in the future.
Since f.read() returns a bytes object, and json.loads expects a str, you'll also need to decode the bytes. The particular encoding depends on what the server decides to send you; in this case the bytes are utf-8 encoded. So use
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)
to decode the bytes.
There is a small typo on the last line. Use
print ("Current temperature in %s is: %s" % (location, temp_f))
to interpolate the string "Current temperature in %s is: %s" with the values (location, temp_f). Note the placement of the quotation mark.
Tip: Since zip is a builtin-function, it is a good practice not to name a
variable zip since this changes the usual meaning of zip making it harder
for others and perhaps future-you to understand your code. The fix is easy: change zip to something else like zip_code.
import urllib.request as request
import json
key = ...
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip_code + ".json"
f = request.urlopen(fileName)
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print ("Current temperature in %s is: %s" % (location, temp_f))

I would recommend using the requests library Python HTTP for Humans., the code below will work on either python2 or 3:
import requests
key = "xxxxxxxxxxx"
# don't shadow builtin zip function
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/{}/geolookup/conditions/q/PA/{}.json".format(key, zip_code)
parsed_json = requests.get(fileName).json()
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
# pass actual variables and use str.format
print ("Current temperature in {} is: {}%f".format(location, temp_f))
Getting the json is simply requests.get(fileName).json(), using str.format is the preferred method and I find less prone to errors, it is also far more feature-rich in comparison to the older printf style formatting.
You can see it works under both 2 and 3 with a sample run:
:~$ python3 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%f
:~$ python2 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%f

Related

Not sure of the Print Structure with YouTube v3 API

So I was creating a script to list information from Google's V3 YouTube API and I used the structure that was shown on their Site describing it, so I'm pretty sure I'm misunderstanding something.
I tried using the structure that was shown to print JUST the Video's Title as a test
and was expecting that to print, however it just throws an error. Error is below
Here's what I wrote below
import sys, json, requests
vidCode = input('\nVideo Code Here: ')
url = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={vidCode}&key=(not sharing the api key, lol)')
text = url.text
data = json.loads(text)
if "kind" in data:
print(f'Video URL: youtube.com/watch?v={vidCode}')
print('Title: ', data['snippet.title'])
else:
print("The video could not be found.\n")
This did not work, however if I change snippet.title to just something like etag the print is successful.
I take it this is because the Title is further down in the JSON List.
I've also tried doing data['items'] which did work, but I also don't want to output a massive chunk of unformatted information, it's not pretty lol.
Another test I did was data['items.snippet.title'] to see if that was what I was missing, also no, that didn't work.
Any idea what I'm doing wrong?
you need to access the keys in the dictionary separately.
import sys, json, requests
vidCode = input('\nVideo Code Here: ')
url = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={vidCode}&key=(not sharing the api key, lol)')
text = url.text
data = json.loads(text)
if "kind" in data:
print(f'Video URL: youtube.com/watch?v={vidCode}')
print('Title: ', data['items'][0]['snippet']['title'])
else:
print("The video could not be found.\n")
To be clear, you need to access the 'items' value in the dictionary which is a list, get the first item from that list, then get the 'snippet' sub object, then finally the title.

How to access specific element of API Get with Python's Request Package?

Hi I am currently using Python 3.X to run the following code:
import requests
jurisdiction = 'us'
name = 'netflix'
limit = 1
r = requests.get('https://opencorporates.com/reconcile?query={%22query%22:%22' + name + '%22,%20%22limit%22:' + str(limit) + ',%20%22jurisdiction_code%22:%22' + jurisdiction + '%22}')
print(type(r))
print(r.text)
The output of this is
<class 'requests.models.Response'>
{"result":[{"id":"/companies/gb/12022722","name":"AMAZON-UK LIMITED","type":[{"id":"/organization/organization","name":"Organization"}],"score":69.0,"match":false,"uri":"https://opencorporates.com/companies/gb/12022722"}],"duration":157.957621}
I want to be able to access the company name from the response and then add it to a list. So I can iterate over a bunch of names/jurisdictions and have a list at the end that I can export to csv (or whatever).
I think that using a to.json or json.dump or something like that might work but I am not sure exactly how to do this? I am open to importing more packages like pandas etc, should the need arise.
Import json and you can read the company names like this:-
import json
data = json.loads(r.text)
#initialize your list
namesList = []
for s in data['result']:
name = s['name']
namesList.append(name)
You can try this.
data = {"result":[{"id":"/companies/gb/12022722","name":"AMAZON-UK LIMITED","type":[{"id":"/organization/organization","name":"Organization"}],"score":69.0,"match":False,"uri":"https://opencorporates.com/companies/gb/12022722"}],"duration":157.957621}
for i in data['result']:
print(i['name'])

JSON output using python including unwanted symbols

I am using Python for the first time to create a simple JSON parser. However, when printing the JSON data to the console, it includes many extra brackets and other symbols that are unwanted. I am also running Python 2.7.10.
import json
from urllib2 import urlopen
response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()
# print(source)
data = json.loads(source)
# print(json.dumps(data, indent=2))
usd_rates = dict()
for item in data['list']['resources']:
name = item['resource']['fields']['name']
price = item['resource']['fields']['price']
usd_rates[name] = price
print(name, price)
And the output is as follows:
When I try to change the python version to 3.7.10:
I think you are actually printing a tuple with python 2 print syntax and the u character is a unicode flag (What exactly do "u" and "r" string flags do, and what are raw string literals?).
Also in python 3 you couldn't use urllib2 but would have to use urllib.request.
This code works for me (python 3.6.5):
import json
from urllib.request import urlopen
response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()
data = json.loads(source)
usd_rates = dict()
for item in data['list']['resources']:
name = item['resource']['fields']['name']
price = item['resource']['fields']['price']
usd_rates[name] = price
print(name, price)
EDIT ---------
From the image you posted it looks like you have python 3 installed but your usr/bin/python is a symbolic link to usr/bin/python2.
If you want to run python 3 by default you could create an alias.
Check this link for more info https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3
(should be valid info for macs too)
Convert name and price to string
print(str(name), str(price))
or
use
name = str(item['resource']['fields']['name'])

Python-JSON - How to parse API output?

I'm pretty new.
I wrote this python script to make an API call from blockr.io to check the balance of multiple bitcoin addresses.
The contents of btcaddy.txt are bitcoin addresses seperated by commas. For this example, let it parse this.
import urllib2
import json
btcaddy = open("btcaddy.txt","r")
urlRequest = urllib2.Request("http://btc.blockr.io/api/v1/address/info/" + btcaddy.read())
data = urllib2.urlopen(urlRequest).read()
json_data = json.loads(data)
balance = float(json_data['data''address'])
print balance
raw_input()
However, it gives me an error. What am I doing wrong? For now, how do I get it to print the balance of the addresses?
You've done multiple things wrong in your code. Here's my fix. I recommend a for loop.
import json
import urllib
addresses = open("btcaddy.txt", "r").read()
base_url = "http://btc.blockr.io/api/v1/address/info/"
request = urllib.urlopen(base_url+addresses)
result = json.loads(request.read())['data']
for balance in result:
print balance['address'], ":" , balance['balance'], "BTC"
You don't need an input at the end, too.
Your question is clear, but your tries not.
You said, you have a file, with at least, more than registry. So you need to retrieve the lines of this file.
with open("btcaddy.txt","r") as a:
addresses = a.readlines()
Now you could iterate over registries and make a request to this uri. The urllib module is enough for this task.
import json
import urllib
base_url = "http://btc.blockr.io/api/v1/address/info/%s"
for address in addresses:
request = urllib.request.urlopen(base_url % address)
result = json.loads(request.read().decode('utf8'))
print(result)
HTTP sends bytes as response, so you should to us decode('utf8') as approach to handle with data.

Wunderground api search bar

I'm currently writting a program that will search for the weather.
I'm trying to create an option where you can search your location however it doesn't seem to be working.
from urllib.request import Request, urlopen
import json
import re
location = input('location you would like to know the weather for')
API_KEY = '<API-KEY>'
url = 'http://python-weather-api.googlecode.com/svn/trunk/ python-weather-api' + API_KEY +'/geolookup/conditions/q/IA/'+ location +'.json'
response = urllib.request.Request(url)
def response as request(url)
json_string = response.read().decode('utf8')
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))
response.close()
I keep on recieving this error
Can't comment yet (reputation too low since I just joined SO), but regarding your "urllib is not defined" issue, that has to do with how you import the urlopen function.
Instead of:
urllib.urlopen(url)
try:
urlopen(url)
EDIT: Here's your code, fixed:
from urllib.request import urlopen
import json
location = input('location you would like to know the weather for')
API_KEY = '<API-KEY>'
url = 'http://api.wunderground.com/api/' + API_KEY + '/geolookup/conditions/q/IA/'+ str(location) +'.json'
response = urlopen(url)
json_string = response.read().decode('utf8')
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))
Works fine for Tama and other cities in IA. Watch out though, place names like Des Moines won't work, because spaces aren't allowed in the URLs - you'll have to take care of that. (The example for the API suggests _ for spaces http://www.wunderground.com/weather/api/d/docs?MR=1). Good luck!
Hey not sure if you are still stuck on this but here is my wunderground project that should have what you're looking for https://github.com/Oso9817/weather_texts
Where you have str.input, you need to use str(location). Right now if you go into a python repl and type str, you will find out that it is a reserved keyword. You want to use the variable location you are getting from the input of the user and not the str object.

Categories

Resources