BeautifulSoup เป็นไลบรารี Python ของบุคคลที่สามที่ใช้ในการแยกวิเคราะห์ข้อมูลจากหน้าเว็บ ช่วยในการขูดเว็บ ซึ่งเป็นกระบวนการดึง ใช้ และจัดการข้อมูลจากแหล่งข้อมูลต่างๆ
การขูดเว็บยังสามารถใช้เพื่อดึงข้อมูลเพื่อวัตถุประสงค์ในการวิจัย ทำความเข้าใจ/เปรียบเทียบแนวโน้มของตลาด ตรวจสอบ SEO และอื่นๆ
บรรทัดด้านล่างสามารถเรียกใช้เพื่อติดตั้ง BeautifulSoup บน Windows -
pip install beautifulsoup4
เรามาดูตัวอย่างกัน −
ตัวอย่าง
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import urllib
url = 'https://en.wikipedia.org/wiki/Algorithm'
html = urlopen(url).read()
print("Reading the webpage...")
soup = BeautifulSoup(html, features="html.parser")
print("Parsing the webpage...")
for script in soup(["script", "style"]):
script.extract() # rip it out
print("Extracting text from the webpage...")
text = soup.get_text()
print("Data cleaning...")
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
text = str(text)
print(text) ผลลัพธ์
Reading the webpage... Parsing the webpage... Extracting text from the webpage... Data cleaning... Recursive C implementation of Euclid's algorithm from the above flowchart Recursion A recursive algorithm is one that invokes (makes reference to) itself repeatedly until a certain condition (also known as termination condition) matches, which is a method common to functional programming…. ….. Developers Statistics Cookie statement
คำอธิบาย
-
แพ็คเกจที่จำเป็นถูกนำเข้าและใช้นามแฝง
-
มีการกำหนดเว็บไซต์
-
เปิด URL และแท็ก "สคริปต์" และแท็ก HTML ที่ไม่เกี่ยวข้องอื่นๆ จะถูกลบออก
-
ฟังก์ชัน "get_text" ใช้เพื่อดึงข้อความจากข้อมูลหน้าเว็บ
-
ช่องว่างส่วนเกินและคำที่ไม่ถูกต้องจะถูกตัดออก
-
ข้อความถูกพิมพ์บนคอนโซล