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

Web Scraping ใน Python ด้วย BeautifulSoup (bs4)

BeautifulSoup เป็นคลาสในโมดูล bs4 ใช้ Parse HTML/XML Documents ทำให้ดึงข้อมูลจากเว็บได้ง่าย

ติดตั้ง

pip install beautifulsoup4 lxml
# lxml: Parser ที่เร็วกว่า built-in html.parser

ตัวอย่างที่ 1: ดึง Link ทั้งหมดจาก HTML String

from bs4 import BeautifulSoup

html_doc = '''
TutorialsPoint
Google
GitHub
Python
'''

soup = BeautifulSoup(html_doc, 'lxml')  # หรือ 'html.parser'

# หา tag  ทั้งหมด ดึง href
for link in soup.find_all('a'):
    print(link.get('href'))
    print(link.text)

ผลลัพธ์

https://www.tutorialspoint.com
TutorialsPoint
https://www.google.com
Google
https://www.github.com
GitHub
https://www.python.org
Python

ตัวอย่างที่ 2: Scrape เว็บจริง (Python.org)

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

html = urlopen("https://www.python.org")
soup = BeautifulSoup(html.read(), 'lxml')

# หา Link ที่มีคำว่า 'python' ใน href
for a in soup.find_all('a', href=True):
    if re.search('python', a['href'], re.I):
        print(a['href'])

เมธอดสำคัญของ BeautifulSoup

Methodคำอธิบาย
find(tag, attrs)หา Element แรกที่ Match
find_all(tag, attrs)หา Element ทั้งหมดที่ Match (คืน List)
select(css_selector)CSS Selector (เช่น 'div.content > p')
select_one(css_selector)CSS Selector Element แรก
get(attr)ดึง Attribute Value
.text / .get_text()ดึง Text Content ภายใน Tag
.attrsDictionary ของ Attributes ทั้งหมด
.parent, .children, .siblingsNavigation ใน DOM Tree

ตัวอย่าง Advance: ดึงข้อมูลตาราง

import pandas as pd

# Pandas มี read_html() ใช้ได้เลยสำหรับ Table
tables = pd.read_html('https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)')
df = tables[0]
print(df.head())

Best Practices

  • ตรวจสอบ robots.txt และ Terms of Service ของเว็บไซต์
  • ใช้ time.sleep() ระหว่าง Request ป้องกัน Block
  • ตั้ง User-Agent Header ให้เหมือน Browser
  • Handle Errors: Timeout, 404, 500, Connection Error
  • ใช้ Session สำหรับ Multiple Requests
  • พิจารณา Scrapy สำหรับ Project ใหญ่/Complex

ตัวอย่าง Request ด้วย Headers

import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}

response = requests.get('https://example.com', headers=headers, timeout=10)
soup = BeautifulSoup(response.content, 'lxml')