Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เข้าถึงอินเทอร์เน็ตด้วย Urllib.Request ใน Python

บทนำ

urllib.request เปิด/อ่าน URLs (HTTP, HTTPS, FTP) ด้วย urlopen ใช้ดึงข้อมูลจาก API, web scraping

การติดตั้ง

urllib มาพร้อม Python (แต่ติดตั้งเพิ่มได้: pip install urllib)

อ่านข้อมูลจาก URL

import urllib.request
request_url = urllib.request.urlopen('https://official-joke-api.appspot.com/random_ten')
print(request_url.read().decode())  # decode bytes → string

บันทึกข้อมูลลงไฟล์

import urllib.request
data = urllib.request.urlopen('https://official-joke-api.appspot.com/random_ten')
data = data.read().decode()
file = open("content.txt", "w+")
file.write(data)
file.close()

ส่งข้อมูลไปยัง URL (POST)

import urllib.parse
import urllib.request

url = 'https://www.google.com/cgi-bin/register.cgi'
values = {'name': 'S Vijay Balaji', 'language': 'Python'}
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
    the_page = response.read()

คำอธิบาย

  • urlopen รองรับหลาย protocols (HTTP, HTTPS, FTP)
  • .read() คืน bytes → .decode() ได้ string
  • POST: encode dict → bytes → Request object → urlopen
  • ใช้กับ: API consumption, web scraping, bot development

โปรเจกต์ตัวอย่าง

Steam Web Scraper: https://github.com/SVijayB/Steam_WebScraper

เอกสาร: https://docs.python.org/3/library/urllib.request.html