Python和Go在處理第三方API時有一些不同的方法和庫。這里將分別介紹這兩種語言在爬蟲方面處理第三方API的方法。
Python有很多庫可以幫助你處理第三方API,以下是一些常用的庫:
Requests:一個簡單易用的HTTP庫,用于發送請求和處理響應。 示例代碼:
import requests
url = "https://api.example.com/data"
headers = {"Authorization": "Bearer your_access_token"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print(data)
else:
print("Error:", response.status_code)
Scrapy:一個強大的爬蟲框架,可以用于處理復雜的爬蟲任務。 示例代碼:
import scrapy
class ApiSpider(scrapy.Spider):
name = "api_spider"
start_urls = ["https://api.example.com/data"]
def parse(self, response):
data = response.json()
for item in data:
yield {
"title": item["title"],
"description": item["description"],
}
Apispec:一個用于描述API的庫,可以幫助你生成和驗證API文檔。 示例代碼:
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowExt
spec = APISpec(
title="Example API",
version="1.0.0",
openapi_version="3.0.0",
info={
"description": "An example API.",
},
servers=["https://api.example.com"],
)
class ExampleResource:
@spec.schema("example")
def get(self):
return {"example": "data"}
spec.path(path="/example", view=ExampleResource.get)
spec.save()
Go語言在處理第三方API時,主要使用標準庫中的"net/http"包。以下是一些示例代碼:
使用"net/http"包發送請求和處理響應:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type ApiResponse struct {
Data []Item `json:"data"`
}
type Item struct {
Title string `json:"title"`
Description string `json:"description"`
}
func main() {
url := "https://api.example.com/data"
headers := map[string]string{
"Authorization": "Bearer your_access_token",
}
resp, err := http.Get(url, headers=headers)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
var apiResponse ApiResponse
err = json.Unmarshal(body, &apiResponse)
if err != nil {
fmt.Println("Error:", err)
return
}
for _, item := range apiResponse.Data {
fmt.Printf("Title: %s, Description: %s\n", item.Title, item.Description)
}
}
使用"github.com/PuerkitoBio/goquery"庫解析HTML內容:
package main
import (
"fmt"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func main() {
url := "https://example.com"
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
var items []string
doc.Find(".item").Each(func(i int, s *goquery.Selection) {
title := s.Find("h2").Text()
description := s.Find("p").Text()
items = append(items, title+", "+description)
})
for _, item := range items {
fmt.Println(item)
}
}
總結:Python和Go在處理第三方API時,都有各自的庫和方法。Python有Requests、Scrapy和Apispec等庫,而Go主要使用標準庫中的"net/http"包以及一些第三方庫如"github.com/PuerkitoBio/goquery"。你可以根據自己的需求和編程經驗選擇合適的語言和庫來處理第三方API。