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

วิธีใช้ BeautifulSoup ดึงชื่อโดเมนของเว็บไซต์ใน Python

บทนำ

BeautifulSoup เป็นไลบรารี Python สำหรับแยกวิเคราะห์ข้อมูลจากหน้าเว็บ ช่วยในการ Web Scraping รวมถึงการประยุกต์ใช้ใน NLP (Natural Language Processing) วิเคราะห์ข้อมูล และสกัดข้อมูลเชิงลึก

Web Scraping ใช้ได้ในงานวิจัย การติดตามแนวโน้มตลาด และ SEO monitoring

การติดตั้ง

pip install beautifulsoup4

ตัวอย่างโค้ด

pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import urllib

url = 'https://en.wikipedia.org/wiki/Algorithm'
parsed_uri = urllib.request.urlparse(url)
domainName = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print("The domain name is : ")
print(domainName)

ผลลัพธ์

The domain name is : https://en.wikipedia.org/

คำอธิบาย

  • นำเข้าแพ็กเกจที่จำเป็น

  • กำหนด URL ของเว็บไซต์

  • ใช้ฟังก์ชัน urlparse เพื่อแยกส่วนประกอบของ URL

  • สร้างชื่อโดเมนจาก scheme (https) และ netloc (en.wikipedia.org)

  • แสดงชื่อโดเมนบนคอนโซล