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

Cách dùng BeautifulSoup trích xuất tên miền (domain) từ URL trong Python

BeautifulSoup là thư viện Python phổ biến cho web scraping, giúp trích xuất, xử lý dữ liệu từ trang web. Nó cũng hỗ trợ các tác vụ tiền xử lý văn bản cho NLP (Xử lý ngôn ngữ tự nhiên).

Web scraping dùng cho nghiên cứu, phân tích xu hướng thị trường, SEO monitoring, v.v.

Cài đặt

pip install beautifulsoup4

Ví dụ: Lấy domain từ URL

import urllib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen

url = 'https://en.wikipedia.org/wiki/Algorithm'
parsed_uri = urllib.parse.urlparse(url)
domain_name = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print("Tên miền là:")
print(domain_name)

Kết quả

Tên miền là:
https://en.wikipedia.org/

Giải thích

  • Nhập thư viện urllib.parse để phân tích URL.
  • Sử dụng urlparse() tách thành các thành phần: scheme (https), netloc (en.wikipedia.org), path, query, fragment.
  • Ghép lại scheme://netloc/ để được domain đầy đủ.

Lưu ý: Ví dụ trên không cần BeautifulSoup vì chỉ xử lý URL. BeautifulSoup dùng khi cần parse nội dung HTML sau khi tải trang.