3

我在 python 中创建了一个程序,我从“wind”网站上抓取了一个值。一切正常,但我想尝试在 Swift 中构建相同的应用程序,但是当我尝试运行程序时,它给出了这个错误:“未经授权的 API 访问!”

但是用 python 抓取效果很好......也许是因为 python 使用了 json?有人可以帮我找出我的 Swift 代码中的错误吗?

这是我的 python 工作代码:

import requests

headers = {'Referer' : 'https://www.windguru.cz/station/219'}    
r = requests.get('https://www.windguru.cz/int/iapi.php?    q=station_data_current&id_station=219&date_format=Y-m-    d%20H%3Ai%3As%20T&_mha=f4d18b6c', headers = headers).json()
print(r)
print(r['wind_max'])

输出是风。

这是我的快速代码:

import UIKit
import SwiftSoup

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURLString = "https://www.windguru.cz/int/iapi.php?    q=station_data_current&id_station=219&date_format=Y-m-    d%20H%3Ai%3As%20T&_mha=f4d18b6c"
        guard let myURL = URL(string: myURLString) else { return }

        do {
            let myHTMLString = try String(contentsOf: myURL,     encoding: .utf8)
            let htmlcontent = myHTMLString
            print(myHTMLString)

            do {
                let doc = try SwiftSoup.parse(htmlcontent)
                do {
                    let element = try doc.select("title").first()
                }
            }

        }catch let error {
            print("error: \(error)")
        }

    }

这会导致 API 访问错误。

4

1 回答 1

0

对于想知道答案的人:

override func viewDidLoad() {
    super.viewDidLoad()

    let headers: HTTPHeaders = [
        "Referer" : "https://www.windguru.cz/station/219"
    ]

Alamofire.request("https://www.windguru.cz/int/iapi.php?q=station_data_current&id_station=219&date_format=Y-m-d%20H%3Ai%3As%20T&_mha=f4d18b6c", headers: headers).responseJSON { response in
        debugPrint(response)
    }
于 2019-07-04T22:07:00.113 回答