Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取python中的好友列表_Python_Api - Fatal编程技术网

获取python中的好友列表

获取python中的好友列表,python,api,Python,Api,我有一个任务,从网站上获取一些测试用户的朋友列表,但从来没有这样做过smth。我们如何在Python中使用API和其他东西 通常避免使用webscraping方法,即直接从网站的HTML代码获取数据,因为网站往往是动态的。万不得已,万不得已 因此,如果网站提供API,请始终首先搜索。正如我所看到的,livejournal确实提供了一种API,但它可能没有提供您所需要的信息 然而,使用API是很简单的。首先,您必须找到要到达的端点,这是一个类似以下链接的多次链接: 从您编写的链接中可以看到,它返回

我有一个任务,从网站上获取一些测试用户的朋友列表,但从来没有这样做过smth。我们如何在Python中使用API和其他东西


通常避免使用webscraping方法,即直接从网站的HTML代码获取数据,因为网站往往是动态的。万不得已,万不得已

因此,如果网站提供API,请始终首先搜索。正如我所看到的,livejournal确实提供了一种API,但它可能没有提供您所需要的信息

然而,使用API是很简单的。首先,您必须找到要到达的端点,这是一个类似以下链接的多次链接: 从您编写的链接中可以看到,它返回:用户最近的条目使用真正的简单联合XML格式进行联合

在Python中找到端点后,可以使用requests模块,根据我的经验,这个模块非常好。使用此模块,您可以向服务端点发送请求以返回查询的数据。可以使用.get方法执行此操作:

response = requests.get(API_ENDPOINT_URL)
然后,如果回复消息的响应代码不是200,您需要检查服务是否没有响应数据:

# throw exception if response code is different than 200
if response.status_code != 200:
    print("There was an error in the response. You didn't get the data you wanted back")
如果一切正常,响应代码为200,那么您很可能拥有所需的数据。现在你只需要按照你的意愿处理它们

请注意,请求不提供对XML数据的支持,但您可以使用python中内置的XML解析器,如本文所述。因此,在获得数据后,您可以使用类似以下内容来处理XML数据:

from xml.etree import ElementTree
tree = ElementTree.fromstring(response.content)
因此,完整的方法如下所示:

import requests
from xml.etree import ElementTree

# note here that 'ohnotheydidnt' is the name of the user of whom you wanna get the data
API_ENDPOINT_URL = "https://ohnotheydidnt.livejournal.com/data/rss"

# send the request and await for a response
response = requests.get(API_ENDPOINT_URL)
# throw exception if response code is different than 200
if response.status_code != 200:
    print("There was an error in the response. You didn't get the data you wanted back")

# get the XML data from the response
tree = ElementTree.fromstring(response.content)

# parse the tree and handle the data

我建议你看一个教程或阅读文档。这个问题不是真正的主题,所以很可能会结束。但该包通常被认为是与web服务(包括API)通信的最佳选择。还有一些标准库模块做类似的事情,但不够全面,例如,最好从检查它们是否有面向公众的API和相关文档开始。很多这样做的网站通常都有一个非常简单的入门部分,可以帮助你开始你的项目。