golang代码

//生成带有cookie的header
func buildHeader(chromeDriverPath string, url string) map[string]string {  
   opts := []selenium.ServiceOption{  
      //selenium.Output(os.Stderr), // Output debug information to STDERR.  
   }  
   //selenium.SetDebug(true)  
   service, err := selenium.NewChromeDriverService(chromeDriverPath, 9515, opts...)   //port端口随便填,保证前后一致
   if err != nil {  
      panic(err) // panic is used only as an example and is not otherwise recommended.  
   }  
   defer service.Stop()  
   caps := selenium.Capabilities{"browserName": "chrome"}  
   wd, err := selenium.NewRemote(caps, "http://127.0.0.1:9515/wd/hub")  
   if err != nil {  
      panic(err)  
   }   defer wd.Quit()  
   if err := wd.Get(url); err != nil {  
      panic(err)  
   }

	// 下面这两行是点击登录的代码.不同的网址肯定不一样
   we, err := wd.FindElement(selenium.ByXPATH, "xxxxxx")  
   we.Click()
   time.Sleep(time.Second * 20)  
   
   cookies, err := wd.GetCookies()  
   var tempList = make([]string, len(cookies))  
   for index, cookie := range cookies {  
      tempList[index] = fmt.Sprintf("%v=%v", cookie.Name, cookie.Value)  
   }   cookieStr := strings.Join(tempList, "; ")  
   header := map[string]string{}  
   header["Cookie"] = cookieStr  
   header["Content-Type"] = "application/json;charset=utf-8"  
   return header
}

//使用上面的header发出request请求
func request(method string, url string, reqBodyStr string) (*http.Response, error) {  
   t := http.DefaultTransport.(*http.Transport).Clone()  
   t.MaxIdleConnsPerHost = 2048  
   t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}  
   t.MaxConnsPerHost = 20  
   client := &http.Client{  
      Timeout:   time.Minute,  
      Transport: t,  
   }  
   req, _ := http.NewRequest(method, url, strings.NewReader(reqBodyStr))  
   return client.Do(req)  
}

python代码

# 生成带有cookie的header
def build_header(url, chrome_driver_path):  
    driver = webdriver.Chrome(chrome_driver_path)  
    driver.implicitly_wait(60)  
    driver.maximize_window()  
    driver.get(url)  
    # 点击登录按钮 ,并等待页面跳转完成 ,此处随意发挥  
    driver.find_element_by_xpath(  
        'xxx').click()  
    time.sleep(20)  
    # 获取cookies  
    cookies = driver.get_cookies()  
    driver.close()  
    temp_list = []  
    for cookie in cookies:  
        temp_list.append('{}={}'.format(cookie['name'], cookie['value']))  
    CookieStr = '; '.join(temp_list)  
    return {  
        "Cookie": CookieStr  
    }
    
# 使用上面的header发出request请求 
def request(url,header):
	resp = requests.get(url=url, headers=header, verify=False)
	return resp

更多推荐