Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Truy cập Internet với module urllib.request trong Python

Giới thiệu

urllib.request mở và đọc URL (thường dùng HTTP). Interface đơn giản: hàm urlopen fetch URL với nhiều giao thức.

Bắt đầu

urllib có sẵn trong Python. (Có thể pip install urllib nếu thiếu).

Kiểm tra urllib.request

Đọc data/source code trang web – hữu ích khi lấy data từ API.

import urllib.request
request_url = urllib.request.urlopen('https://official-joke-api.appspot.com/random_ten')
print(request_url.read().decode())  # decode() để ra plain text thay vì bytes

Lưu data từ API ra file

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

Lưu ý: urlopen hoạt động giống nhau cho FTP, HTTPS, các giao thức khác.

Gửi dữ liệu đến URL (POST request)

Dùng urllib.request + urllib.parse.

import urllib.parse, 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()

Kết luận

urllib.request lấy tài nguyên Internet, parse API, scrape web. Dự án ví dụ: Steam WebScraper. Xem tài liệu.