我想使用 Python 2.7.3 从 Sharepoint 中提取数据。这是我的代码:
import requests
import urlparse
import json
from requests_ntlm import HttpNtlmAuth
user_credentials = {
'username' : 'my_username',
'password' : 'my_password',
'domain' : 'my_domain'
}
# Creating a class for Authentication
class UserAuthentication:
def __init__(self, username, password, domain, site_url):
self.__username = username
self.__password = password
self.__domain = domain
self.__site_url = site_url
self.__ntlm_auth = None
def authenticate(self):
login_user = self.__domain + "\\" + self.__username
user_auth = HttpNtlmAuth(login_user, self.__password)
self.__ntlm_auth = user_auth
# Create header for the http request
my_headers = {
'accept' : 'application/json;odata=verbose',
'content-type' : 'application/json;odata=verbose',
'odata' : 'verbose',
'X-RequestForceAuthentication' : 'true'
}
# Sending http get request to the sharepoint site
result = requests.get(self.__site_url, auth=user_auth, headers=my_headers, verify=False)
# Requests ignore verifying the SSL certificates if you set verify to False
# Checking the status code of the requests
if result.status_code == requests.codes.ok: # Value of requests.codes.ok is 200
return True
else:
result.raise_for_status()
def sharepoint_get_request(self, endpoint_uri):
headers = {
'accept' : 'application/json;odata=verbose',
'content-type' : 'application/json;odata=verbose',
'odata' : 'verbose',
'X-RequestForceAuthentication' : 'true'
}
url = urlparse.urljoin(self.__site_url, endpoint_uri)
result = requests.get(url, auth=self.__ntlm_auth, headers=headers,
verify=False)
return result
if __name__ == "__main__":
username = user_credentials['username']
password = user_credentials['password']
domain = user_credentials['domain']
site_url = "https://sharepoint.com/sites/my_sharepoint"
auth_object = UserAuthentication(username, password, domain, site_url)
result = auth_object.authenticate()
if result:
print("Successfully login to sharepoint site")
# Want information about a specific list
listname = "my_list"
endpoint_uri = "_api/web/lists/getbytitle('" + listname + "')"
result = auth_object.sharepoint_get_request(endpoint_uri)
print result.status_code #200
list_info = result.json() # ValueError: No JSON object could be decoded
result = auth_object.sharepoint_get_request(endpoint_uri)
for element in result.json()['d']['results']:
print("{}".format(element['Title']))
我可以成功登录到sharepoint站点,“sharepoint_get_request”结果的状态码是200,但问题是result.json()给了我错误:ValueError: No JSON object could be decoded。
200 状态码结果怎么可能没有有效的 json 对象?可以是 HTML 页面吗?在这种情况下,如何在 Python 2.7.3 中解析 HTML 页面?
先感谢您