2015-08-24 4 views
0

Я удивляюсь, что есть способ написать в электронную таблицу google с помощью Python. Найдено python-gdata-client библиотека, установленная со всеми зависимостями. Используя этот код, приведенный ниже, но он не работаетНапишите в таблицу google с помощью Python

import time 
import gdata.spreadsheet.service 

email = '[email protected]' 
password = 'pwd' 
weight = '180' 
# Find this value in the url with 'key=XXX' and copy XXX below 
spreadsheet_key = 'pRoiw3us3wh1FyEip46wYtW' 
# All spreadsheets have worksheets. I think worksheet #1 by default always 
# has a value of 'od6' 
worksheet_id = 'Sheet1' 

spr_client = gdata.spreadsheet.service.SpreadsheetsService() 
spr_client.email = email 
spr_client.password = password 
spr_client.source = 'Example Spreadsheet Writing Application' 
spr_client.ProgrammaticLogin() 

# Prepare the dictionary to write 
dict = {} 
dict['date'] = time.strftime('%m/%d/%Y') 
dict['time'] = time.strftime('%H:%M:%S') 
dict['weight'] = weight 
print dict 

entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id) 
if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): 
    print "Insert row succeeded." 
else: 
    print "Insert row failed." 

Это ошибка говорит -

Traceback (most recent call last): 
    File "D:/steve/test.py", line 28, in <module> 
    entry = spr_client.InsertRow(dict, spreadsheet_key, worksheet_id) 
    File "C:\Python27\lib\site-packages\gdata\spreadsheet\service.py", line 338, in InsertRow 
    converter=gdata.spreadsheet.SpreadsheetsListFromString) 
    File "C:\Python27\lib\site-packages\gdata\service.py", line 1235, in Post 
    media_source=media_source, converter=converter) 
    File "C:\Python27\lib\site-packages\gdata\service.py", line 1346, in PostOrPut 
    redirects_remaining - 1, media_source, converter=converter) 
    File "C:\Python27\lib\site-packages\gdata\service.py", line 1328, in PostOrPut 
    return converter(result_body) 
    File "C:\Python27\lib\site-packages\gdata\spreadsheet\__init__.py", line 376, in SpreadsheetsListFromString 
    xml_string) 
    File "C:\Python27\lib\site-packages\atom\__init__.py", line 92, in optional_warn_function 
    return f(*args, **kwargs) 
    File "C:\Python27\lib\site-packages\atom\__init__.py", line 126, in CreateClassFromXMLString 
    tree = ElementTree.fromstring(xml_string) 
    File "<string>", line 124, in XML 
ParseError: mismatched tag: line 944, column 4 
+1

Можете ли вы добавить полный стек? Здесь не 944 строки кода – Holloway

+0

Когда вы задаете вопросы, вы всегда должны публиковать полные трассировки. – Alik

+0

Извините, я сделаю это сейчас –

ответ

4

Вы используете ClientLogin method, который был устаревшим, начиная с 20 апреля 2012 года Кажется, что Google превратился его выезд 26 мая 2015 года.

Вместо этого используйте OAuth2.

+0

Привет, Alik, Как это сделать, я немного новичок в программировании API –

+0

@ShekharSamanta Я дал вам конкретную ссылку с примерами в Python. Прочтите его и попробуйте реализовать – Alik

+0

Привет, я пробовал все описанные здесь шаги - http://gspread.readthedocs.org/en/latest/oauth2.html. Но без успеха, Traceback: Traceback (последний последний звонок): Файл «D: \ steve \ get_oauth2_token.py», строка 12, в wks = gc.open («siteprice») Файл «C: \ Python27 \ lib \ site-packages \ gspread \ client.py ", строка 150, открыта raise SpreadsheetNotFound ТаблицаNotFound –

0

, как Алик уже упоминалось выше, начиная с 2015 года, и нужно использовать oauth2client, которые можно установить, запустив:

pip install oauth2client 

здесь пример кода для входа в систему:

import gspread 
from oauth2client.service_account import ServiceAccountCredentials 


# trying to log in 
scope = ['https://spreadsheets.google.com/feeds'] 
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) # u can download the json file from google's api manager 
client = gspread.authorize(creds) # authorize access 

# defining the sheet that we will work on 
sheet = client.open('sheetName').sheet1 # getting a sheet to work on 

Я знаю, что его было год с тех пор, как вы задали свой вопрос, но я надеюсь, что помог кому-то другому.

Смежные вопросы