Python สามารถใช้เพื่อเข้าถึงเว็บเพจและส่งข้อมูลไปยังเว็บเซิร์ฟเวอร์ได้ มีโมดูลหลายตัว เช่น httplib, urllib, httplib2 แต่โมดูล requests เป็นที่นิยมมากที่สุดเพราะใช้งานง่ายและเขียนโค้ดได้สั้น แต่มีความสามารถครบครันสำหรับการทำงานกับเมธอด GET และ POST
เมธอด GET
เมธอด GET เป็นส่วนหนึ่งของโมดูล requests ใช้สำหรับดึงข้อมูลจาก URL ของเว็บ ในตัวอย่างด้านล่างเราจะเข้าถึงเว็บไซต์ตัวอย่างและตรวจสอบการตอบกลับต่างๆ ผ่านเมธอด get เช่น เข้ารหัส (Encoding) รหัสสถานะ (Response code) เวลาตอบสนอง (Response time) หัวข้อ (Header) และส่วนของเนื้อหา (Body)
ตัวอย่าง
import requests
req = requests.get('https://www.tutorialspoint.com/')
# เข้ารหัสหน้าเว็บ
e = req.encoding
print("Encoding:", e)
# รหัสสถานะการตอบกลับ
s = req.status_code
print("Response code:", s)
# เวลาตอบสนอง
t = req.elapsed
print("Response Time:", t)
# หัวข้อ Content-Type
t = req.headers['Content-Type']
print("Header:", t)
# เนื้อหาหน้าเว็บ (200 ตัวอักษรแรก)
z = req.text
print("\nSome text from the web page:\n", z[0:200])
ผลลัพธ์
Encoding: UTF-8 Response code: 200 Response Time: 0:00:00.103850 Header: text/html; charset=UTF-8 Some text from the web page: <!--<html lang="en-US"> <!--<![endif]--> <!--<head> Bas -->
เมธอด POST
เมธอด POST ใช้สำหรับส่งข้อมูลไปยังเซิร์ฟเวอร์ โดยทั่วไปจะส่งผ่านฟอร์ม เพื่อสร้างหรืออัปเดตข้อมูลบนเซิร์ฟเวอร์ โมดูล requests มีเมธอด post ที่สามารถส่งข้อมูลได้โดยตรง โดยรับ URL และพารามิเตอร์ข้อมูล
ในตัวอย่างด้านล่าง เราจะส่งข้อมูลไปยังเว็บไซต์ httpbin.org ผ่านเมธอด POST และดูผลการตอบกลับ
ตัวอย่าง
import requests
in_values = {'username': 'Jack', 'password': 'Hello'}
res = requests.post('https://httpbin.org/post', data=in_values)
print(res.text)
ผลลัพธ์
{
"args": {},
"data": "",
"files": {},
"form": {
"password": "Hello",
"username": "Jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "28",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5ef75488-969f97a68bb72642b97b6d50"
},
"json": null,
"origin": "122.xxx.yy.zzz",
"url": "https://httpbin.org/post"
}