簡體   English   中英

如何在 Go 中重用 HTTP 請求實例

[英]How to reuse HTTP request instance in Go

我正在構建一個 API 從網頁上抓取一些數據。

為此,我需要向主頁發送一個 GET 請求,從 HTML 中抓取一個“RequestVerificationToken”,然后使用用戶名、密碼和 RequestVerificationToken 向同一個 URL 發送另一個 POST 請求。

我以前可以用 Python 做到這一點:

session_requests = requests.session()
result = session_requests.get(LOGIN_URL)
parser = createBS4Parser(result.text)
return parser.find('input', attrs={'name': '__RequestVerificationToken'})["value"]

 pageDOM = session_requests.post(
        LOGIN_URL,
        data=requestPayload, //RequestVerificationToken is in here
        headers=requestHeaders
 )

似乎當我在 Python 中重用session_requests變量時,它正在重用 HTTP 請求的前一個實例。

但是,當我嘗試在 Go 中執行此操作時,由於令牌無效而出現錯誤。 我認為這是因為對於 POST 請求,Go 正在使用一個新實例。

有什么方法可以讓我從 Go 獲得與 Python 相同的行為?

 package main

 import (
    "fmt"
    "log"

   "github.com/gocolly/colly"
   "github.com/gocolly/colly/proxy"
     )

  func main() {
//initiates the configuration
c := colly.NewCollector(colly.AllowURLRevisit())
//defining the proxy chain
revpro, err := proxy.RoundRobinProxySwitcher("socks5://127.0.0.1:9050", "socks5://127.0.0.1:9050")
if err != nil {
    log.Fatal(err)
}
c.SetProxyFunc(revpro)
//parsing the required field from html we are extracting the csrf_token required for the login
c.OnHTML("form[role=form] input[type=hidden][name=CSRF_TOKEN]", func(e *colly.HTMLElement) {
    csrftok := e.Attr("value")
    fmt.Println(csrftok)
    //posting the csrf value along with password
    err := c.Post("https://www.something.com/login.jsp", map[string]string{"CSRF_TOKEN": csrftok, "username": "username", "password": "password"})
    if err != nil {
        log.Fatal(err)
    }
    return
})
//The website to visit
c.Visit("https://www.something.com/login.jsp")
//maintaining the connection using clone not initiating a callback request
d := c.Clone()
d.OnHTML("a[href]", func(e *colly.HTMLElement) {
    link := e.Attr("href")
    fmt.Printf("Link found: %q -> %s\n", e.Text, link)

})

d.Visit("https://skkskskskk.htm")
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM