[英]Fetch list of friends in python
通常避免使用網絡抓取方法,直接從網站的 HTML 代碼獲取數據,因為網站往往是動態的。 使用網絡抓取作為最后的手段!
因此,如果網站提供 API,請始終先搜索。 正如我所見,livejournal 確實提供了一種 API 但也許它沒有為您提供您正在尋找的信息。
盡管如此,使用 API 還是很簡單的。 首先,您必須找到要到達的端點,即很多時候是這樣的鏈接: https://exampleusername.livejournal.com/data/rss從您編寫的鏈接中可以看到返回: A user's recent entries syndicated使用 Real Simple Syndication 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.