Bài viết này hướng dẫn chi tiết cách trích xuất dữ liệu từ website sử dụng GraphQL với ngôn ngữ lập trình Python. Nội dung tập trung vào việc lấy dữ liệu từ trang Axie.zone, áp dụng kiến thức về Python và cơ chế tải dữ liệu web.
Bài viết này đòi hỏi kiến thức cơ bản về Python và cách website tải dữ liệu. Đảm bảo bạn đã nắm vững những kiến thức này để hiểu và áp dụng hiệu quả.
Mô tả ảnh Python code
Tìm hiểu về GraphQL và Trích xuất Dữ liệu
GraphQL là một ngôn ngữ truy vấn và thao tác dữ liệu cho API, cũng là một runtime server-side để thực hiện các truy vấn đó với dữ liệu hiện có. GraphQL được thiết kế để làm cho API nhanh hơn, linh hoạt hơn và thân thiện với nhà phát triển hơn so với REST.
Trích xuất Dữ liệu từ Axie.zone với Python
Mục tiêu của chúng ta là trích xuất dữ liệu từ Axie.zone. Dưới đây là đoạn mã Python hoàn chỉnh để thực hiện việc này. Đoạn mã này sử dụng thư viện requests
để gửi yêu cầu POST đến GraphQL endpoint và thư viện json
để xử lý dữ liệu JSON.
import requests
import json
url = "https://axieinfinity.com/graphql-server-v2/graphql"
payload = json.dumps({
"operationName": "GetAxieBriefList",
"query": "query GetAxieBriefList($auctionType: AuctionType, $criteria: AxieSearchCriteria, $from: Int, $sort: SortBy, $size: Int, $owner: String) { axies(auctionType: $auctionType, criteria: $criteria, from: $from, sort: $sort, size: $size, owner: $owner) { total results { ...AxieBrief __typename } __typename } } fragment AxieBrief on Axie { id name stage class breedCount image title genes battleInfo { banned __typename } auction { currentPrice currentPriceUSD __typename } stats { ...AxieStats __typename } parts { id name class type specialGenes __typename } __typename } fragment AxieStats on AxieStats { hp speed skill morale __typename }",
"variables": {
"auctionType": "Sale",
"criteria": {
"classes": [
"Dusk"
],
"parts": [
"mouth-tiny-turtle",
"mouth-tiny-carrot",
"mouth-dango",
"horn-lagging",
"horn-laggingggggg",
"back-snail-shell",
"back-starry-shell",
"tail-thorny-caterpillar",
"tail-thorny-catterpilar"
],
"hp": None,
"speed": [
46,
61
],
"skill": None,
"morale": None,
"breedCount": None,
"pureness": [],
"numMystic": [],
"title": None,
"region": None,
"stages": [
3,
4
]
},
"from": 24,
"size": 12,
"sort": "PriceAsc",
"owner": None
}
})
headers = {
'authority': 'axieinfinity.com',
'sec-ch-ua': '"Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"',
'accept': '*/*',
'content-type': 'application/json',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
'origin': 'https://axie.zone',
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://axie.zone/',
'accept-language': 'en-US,en;q=0.9,vi;q=0.8'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Giải thích Chi tiết Đoạn Mã
Đoạn mã trên thực hiện các bước sau:
Import thư viện:
requests
để gửi HTTP request vàjson
để làm việc với dữ liệu JSON.Định nghĩa URL: URL của GraphQL endpoint.
Tạo Payload: Payload chứa câu truy vấn GraphQL và các biến cần thiết. Bạn có thể tùy chỉnh câu truy vấn và biến để lấy dữ liệu mong muốn.
Định nghĩa Headers: Headers chứa thông tin về request, ví dụ như
user-agent
,content-type
.Gửi Request: Sử dụng
requests.request("POST", url, headers=headers, data=payload)
để gửi yêu cầu POST đến GraphQL endpoint.In Kết Quả: In dữ liệu trả về từ server.
Kết Luận
Bài viết đã hướng dẫn cách trích xuất dữ liệu từ website sử dụng GraphQL và Python. Hy vọng bài viết này hữu ích cho bạn. Hãy thử nghiệm và áp dụng cho dự án của mình.
Discussion about this post