This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 3 years ago.
(Scrapy)I need help with the next code:
def parse_item(self, response):
ml_item = MercadoItem()
#info de producto
ml_item['nombre'] = response.xpath('//h1[#class="title"]/text()').extract()
ml_item['web'] = response.xpath('/html/body/div[1]/div/div/div[1]/main/div/div[1]/div[2]/div[1]/div/div[4]/a/#href').extract()
script_data = response.xpath('string(/html/head/script[3]/text()').extract()
decoded_data = json.loads(script_data)
ml_item['datos'] = decoded_data["telephone"]
ml_item['direccion'] = response.xpath('/html/body/div[1]/div/div/div[1]/main/div/div[1]/div[2]/div[1]/div/span[2]/text()').extract()
self.item_count += 1
if self.item_count > 5:
raise CloseSpider('item_exceeded')
yield ml_item
I use decoded Json for obtain phone number only but the console return me a error
script_data contains the script
File "/mercadolibre-scrapy-master/mercado/spiders/spiderq.py", line 88
ml_item['direccion'] = response.xpath('/html/body/div[1]/div/div/div[1]/main/div/div[1]/div[2]/div[1]/div/span[2]/text()').extract()
^ IndentationError: unexpected indent
The script is:
{"#context":"http://schema.org","#type":"LocalBusiness","name":"Clínica Dental Castellana 23","description":".TU CLÍNICA DENTAL DE REFERENCIA EN MADRID","telephone":"+34912298837","address":{"#type":"PostalAddress","streetAddress":"Castellana 23","addressLocality":"MADRID","addressRegion":"Madrid","postalCode":"28003"}}
Check the line reported by the error, the indentation used to align that line is different from the indentation used for the previous one, for example you may have 4 spaces before and 1 tab after, the may look the same, but they are different for the Python interpreter.
Related
This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 1 year ago.
For some reason when I run this code I get an unexpected indent error on the #staticmethod line, but I have no idea why! Everything is properly indented, but this is causing all of my methods to raise errors in code post. Also, I removed a few other methods from the class to shorten the code I'm posting on here.
class Reservation:
"""A data type that represents a hotel room booking system."""
booking_numbers = []
#staticmethod
def get_reservations_from_row(room_obj, list_tuples):
reservation_dict = {}
booking_num_list = []
date_list = []
for element in list_tuples:
year, month, day, short_str = element
list_short_str = short_str.split('--')
booking_num = int(list_short_str[0])
name = list_short_str[1]
if booking_num not in booking_num_list:
booking_num_list.append(booking_num)
date = datetime.date(year, month, day)
date_list.append(date)
for element in booking_num_list:
print(date_list)
date_list.sort()
value = Reservation(name, room_obj, date_list[0], date_list[len(date_list)-1], element)
reservation_dict[element] = reservation_dict.get(element, []) + value
return reservation_dict
Traceback (most recent call last):
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "/Users/myname/Downloads/reservation.py", line 74
#staticmethod
^
IndentationError: unexpected indent
It seems that you have used the tab for indentation.
Remove the tab and insert 4 spaces it will work for you
This question already has answers here:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
(24 answers)
Closed 1 year ago.
I've been trying to do some API queries to get some missing data in my DF. I'm using grequest library to send multiple request and create a list for the response object. Then I use a for loop to load the response in a json to retrieve the missing data. What I noticed is that when loading the data using .json() from the list directly using notition list[0].json() it works fine, but when trying to read the list and then load the response into a json, This error comes up : JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Here's my code :
import requests
import json
import grequests
ls = []
for i in null_data['name']:
url = 'https://pokeapi.co/api/v2/pokemon/' + i.lower()
ls.append(url)
rs = (grequests.get(u) for u in ls)
s = grequests.map(rs)
#This line works
print(s[0].json()['weight']/10)
for x in s:
#This one fails
js = x.json()
peso = js['weight']/10
null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
<ipython-input-21-9f404bc56f66> in <module>
13
14 for x in s:
---> 15 js = x.json()
16 peso = js['weight']/10
17 null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
One (or more) elements are empty.
So:
...
for x in s:
if x != ""
js = x.json()
peso = js['weight']/10
null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
...
or
...
for x in s:
try:
js = x.json()
peso = js['weight']/10
null_data.loc[null_data['name'] == i.capitalize(), 'weight_kg'] = peso
except json.JSONDecodeError as ex: print("Failed to decode(%s)"%ex)
...
The first checks if x is an empty string while the other tries to decode every one but upon an exception just prints an error message instead of quitting.
This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 2 years ago.
IndentationError: unexpected unindent WHY? Here's my code:
from praw.models import MoreComments
import praw
import giris
import time
import os
def bot_login():
print("Loggin in...")
r = praw.Reddit(username = giris.username,
password = giris.password,
client_id = giris.client_id,
client_secret = giris.client_secret,
user_agent = "karton_bardak_bot")
print("Logged in!")
return r
info="""
\n
\n
\n
^(ben bot) \n
\n
^(bruh)
"""
subreddit=r.subreddit("shithikayeler")
def run_bot(r, comments_replied_to):
print("Obtaining 25 comments...")
for submission in subreddit.new():
toReply=True
for top_level_comment in submission.comments:
if isinstance(top_level_comment, MoreComments):
continue
if not submission.is_self:
toReply=False
if top_level_comment.author=="karton_bardak_bot" or submission.selftext=='':
toReply=False
print("PASSED "+ submission.url)
log.write("PASSED "+ submission.url+"\n")
if toReply:
try:
new=reply(submission.selftext, info)
submission.reply(new)
except Exception as e:
log.write("ERROR: " + str(e) + " on submission " + submission.url)
print("REPLIED "+ submission.url)
log.write("REPLIED "+submission.url+"\n")
try:
time.sleep(60)
r = bot_login
while True:
run_bot(r)
It says:
File "bot.py", line 57
r = bot_login
^
IndentationError: unexpected unindent
Why? I have checked a thousands times and I can't find the problem. Pls help.
Because you start a
try:
block with out giving it the needed
except:
part... exactly here:
try:
time.sleep(60)
r = bot_login
so it complains about r = bot_login being maliciously wrong indented.
The code either expects you to stay inside the try: indentation to add more code or ex-dent once and add the except ... : part of the statement followed by another indent for it`s code.
See python.org tutorial about handling exceptions
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#!/usr/bin/env python
import requests, json
userinput = raw_input('Enter a keyword: ')
getparams = {'order':'desc', 'sort':'votes', 'intitle':userinput, 'site':'stackoverflow', 'filter': '!5-HwXhXgkSnzI0yfp0WqsC_-6BehEi(fRTZ7eg'}
r = requests.get('https://api.stackexchange.com/2.2/search', params=getparams)
result = json.loads(r.text)
if result['has_more'] == False:
print 'Error given.'
else:
for looping in result['items']:
print ''
print ''
print 'Title:', looping['title']
#print 'Question:', looping['body']
print 'Link:', looping['link']
if looping['is_answered'] == True:
try:
print 'Answer ID#:', looping['accepted_answer_id']
newparams = {'order':'desc', 'sort':'votes', 'site':'stackoverflow', 'filter': '!4(Yrwr)RRK6oy2JSD'}
newr = requests.get('https://api.stackexchange.com/2.2/answers/', looping['accepted_answer_id'], params=newparams)
newresult = json.loads(newr.text)
print newresult['items'][0]['body']
except KeyError: print 'No answer ID found.'
print ''
print ''
I am trying to make a request such as "https://api.stackexchange.com/2.2/answers/12345 (User inputs 12345)" but I don't know how to do that. And if I include a string it returns error. Help, please?
I am getting this error:
Enter a keyword: php
Title: How can I prevent SQL-injection in PHP?
Link: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
Answer ID#: 60496
Traceback (most recent call last):
File "./warrior.py", line 25, in <module>
newr = requests.get('https://api.stackexchange.com/2.2/answers/', looping['accepted_answer_id'], params=newparams)
TypeError: get() takes exactly 1 argument (3 given)
update the request line as
newr = requests.get('https://api.stackexchange.com/2.2/answers/'+str(looping['accepted_answer_id']), params=newparams)
you need to concatenate the looping['accepeted answer']
This question already has answers here:
Python print statement “Syntax Error: invalid syntax” [duplicate]
(2 answers)
Closed 8 years ago.
I am new to Python and I am trying to run the following lines in Python 3.4. The file is downloaded from Yelp.com and is ready-to-use:
url_params = url_params or {}
url = 'http://{0}{1}?'.format(host, path)
consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)
oauth_request.update(
{
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': TOKEN,
'oauth_consumer_key': CONSUMER_KEY
}
)
token = oauth2.Token(TOKEN, TOKEN_SECRET)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
print 'Querying {0} ...'.format(url)
In the last line:
print 'Querying {0} ...'.format(url) I get an error message: SyntaxError: invalid syntax
In Python 3 and up the argument to print has to be inside parenthesis:
print('Querying {0} ...'.format(url))
In Python 3x you have to put paranthesis in print function.
print ('Querying {0} ...'.format(url))
For example you can't do this;
print "hello"
You have to write that like;
print ("hello")