[Robot][Python]如何送出Get, Post的HttpRequest

  • 2018
  • 0
  • 2018-09-06

[Robot][Python]如何送出Get, Post的HttpRequest

Get:
python有許多的框架方便debug httprequest,即使只是一個簡單的httprequest+get比起其他程式語言都來的方便,如下是一個基本的request台灣雅虎的網頁:

import requests
res = requests.get("https://tw.yahoo.com/")
print(res.text)

可以發現很輕易的就可以取得網頁的內容:(IDE使用PyCharm)

同樣的網站內容如果要用C#去取得,Header必需要做額外的設定、才能取得結果,下面的範例如果將Header的設定拿掉,就會取不到結果喔:

string result = "";
HttpWebRequest request;
CookieContainer cookies = new CookieContainer();

request = WebRequest.Create("https://tw.yahoo.com/") as HttpWebRequest;
request.Method = "GET";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";

request.Headers.Set("Accept-Language", "zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4,zh-CN;q=0.2");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36";
request.CookieContainer = cookies;                       

using (var response = (HttpWebResponse)request.GetResponse())
{
	using (var responseStream = response.GetResponseStream())
	{
		using (var reader = new StreamReader(responseStream, Encoding.UTF8))
		{
			result = reader.ReadToEnd();
		}
	}
}

此外,Python如果要保留Session的話,也只需要加上一行:

rs = requests.session()
import requests
rs = requests.session()
res = rs.get("https://tw.yahoo.com/")
print(res.text)

Post:

post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)



參考資料:
https://stackoverflow.com/questions/4476373/simple-url-get-post-function-in-python