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

Python Tools สำหรับ Web Scraping

Web Scraping คือการดึงข้อมูลจากเว็บไซต์ แปลงข้อมูลไม่มีโครงสร้าง (unstructured) บนเว็บ ให้เป็นข้อมูลมีโครงสร้าง (structured)

เครื่องมือยอดนิยมใน Python 3

  • urllib.request - Built-in (Python 3)
  • Requests - HTTP library ที่ใช้งานง่ายที่สุด
  • BeautifulSoup - HTML/XML parser
  • lxml - High-performance parser
  • Selenium - Browser automation (JavaScript rendering)
  • MechanicalSoup - Stateful browser simulation

1. urllib.request (Built-in)


from urllib.request import urlopen

html = urlopen("https://www.tutorialspoint.com/")
print(html.read()[:500])  # แสดง 500 ตัวอักษรแรก

2. Requests (แนะนำสำหรับ HTTP)


pip install requests

import requests

resp = requests.get('https://www.tutorialspoint.com/')
print("Encoding:", resp.encoding)
print("Status:", resp.status_code)
print("Elapsed:", resp.elapsed)
print("URL:", resp.url)
print("History:", resp.history)
print("Content-Type:", resp.headers['Content-Type'])

ผลลัพธ์


Encoding: UTF-8
Status: 200
Elapsed: 0:00:00.205727
URL: https://www.tutorialspoint.com/
History: []
Content-Type: text/html; charset=UTF-8

3. BeautifulSoup (Parsing HTML)


pip install beautifulsoup4

from bs4 import BeautifulSoup
import requests

resp = requests.get("https://www.tutorialspoint.com/")
soup = BeautifulSoup(resp.text, 'html.parser')

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

4. lxml (High Performance Parser)


pip install lxml

from lxml import etree

root = etree.Element('html')
etree.SubElement(root, 'head')
etree.SubElement(root, 'title')
etree.SubElement(root, 'body')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))

ผลลัพธ์



  
  
  <body/>
</html>
</code></pre>

<h2>5. Selenium (JavaScript-heavy Sites)</h2>
<pre><code>
pip install selenium
# ต้องติดตั้ง WebDriver (ChromeDriver, GeckoDriver) แยกต่างหาก

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service)
driver.get('https://www.tutorialspoint.com/')
print(driver.title)
driver.quit()
</code></pre>

<p style="text-align: center;"><img loading='lazy' alt='Python Tools สำหรับ Web Scraping' src="https://th.wsxdn.com/UploadFiles_2907/202204/2022040701542865.jpg" alt="Selenium Browser" /></p>

<h2>6. MechanicalSoup (Form Handling)</h2>
<pre><code>
pip install MechanicalSoup

import mechanicalsoup

browser = mechanicalsoup.StatefulBrowser()
resp = browser.open("https://www.tutorialspoint.com/")
print("Response:", resp)
print("URL:", browser.get_url())

# ตามลิงก์และ submit form
browser.follow_link("forms")
print("New URL:", browser.get_url())
</code></pre>

<h2>สรุปการเลือกใช้</h2>
<table>
  <thead><tr><th>Tool</th><th>เหมาะสำหรับ</th><th>JavaScript</th><th>ความยาก</th></tr></thead>
  <tbody>
    <tr><td>urllib</td><td>Simple GET, ไม่ต้องติดตั้ง</td><td>ไม่รองรับ</td><td>ต่ำ</td></tr>
    <tr><td>Requests</td><td>HTTP ทุกประเภท, API</td><td>ไม่รองรับ</td><td>ต่ำ</td></tr>
    <tr><td>BeautifulSoup</td><td>Parse HTML/XML</td><td>ไม่รองรับ</td><td>ต่ำ-ปานกลาง</td></tr>
    <tr><td>lxml</td><td>Parse เร็ว, XML ซับซ้อน</td><td>ไม่รองรับ</td><td>ปานกลาง</td></tr>
    <tr><td>Selenium</td><td>JS rendering, SPA, Login flow</td><td><strong>รองรับ</strong></td><td>สูง</td></tr>
    <tr><td>MechanicalSoup</td><td>Form submit, Session, Cookie</td><td>ไม่รองรับ</td><td>ปานกลาง</td></tr>
  </tbody>
</table>

<p><strong>แนวทางปฏิบัติ:</strong> เริ่ม Requests + BeautifulSoup ก่อน ถ้าเว็บใช้ JS เยอะ纔用 Selenium</p>
            </article>
            <div class="ad ad5">
<script language='javascript' src='/ad/w.js'></script>
</div>
            <section id="turn-page" class="t-over">
                <div class="f-start f-align">
                    <i><img loading='lazy' src="https://th.wsxdn.com/css/img/sanjiao.svg" alt=""></i>
                    <a class='LinkPrevArticle' href='https://th.wsxdn.com/db044w/wu448o/1004106443.html' >อ่านและเขียนไฟล์ Excel ด้วย Python openpyxl</a> 
                </div>
                <div class="f-start f-align">
                    <i><img loading='lazy' src="https://th.wsxdn.com/css/img/sanjiao.svg" alt=""></i>
                    <a class='LinkNextArticle' href='https://th.wsxdn.com/db044w/wu448o/1004106445.html'  >โปรแกรม Python สร้างเกม Rock Paper Scissors (เป่ายิ้งฉุบ)</a> 
                </div>
            </section>
            <section class="box1-3">
                <ol class="f-between">

                    <li class="aList-2 aList f-between f-align">
                        <div>
                            <a href="https://th.wsxdn.com/db044w/wu448o/1004106241.html" class="title">
                                <p class="r-over r-over-2" title="Web Scraping ด้วย Python และ Scrapy">Web Scraping ด้วย Python และ Scrapy</p>
                            </a>
                        </div>
                    </li>

                    <li class="aList-2 aList f-between f-align">
                        <div>
                            <a href="https://th.wsxdn.com/db044w/wu448o/1004106255.html" class="title">
                                <p class="r-over r-over-2" title="การดึงข้อมูลเว็บด้วย lxml ใน Python">การดึงข้อมูลเว็บด้วย lxml ใน Python</p>
                            </a>
                        </div>
                    </li>

                    <li class="aList-2 aList f-between f-align">
                        <div>
                            <a href="https://th.wsxdn.com/ge046y/pn443i/1004136961.html" class="title">
                                <p class="r-over r-over-2" title="31 เครื่องมือ Web Scraping ที่ดีที่สุด ปี 2024: ใช้ง่าย มีพลัง น่าเชื่อถือ">31 เครื่องมือ Web Scraping ที่ดีที่สุด ปี 2024: ใช้ง่าย มีพลัง น่าเชื่อถือ</p>
                            </a>
                        </div>
                    </li>

                    <li class="aList-2 aList f-between f-align">
                        <div>
                            <a href="https://th.wsxdn.com/ec041w/ge414y/1004148987.html" class="title">
                                <p class="r-over r-over-2" title="เครื่องมือออกแบบเว็บสำหรับมืออาชีพ: คัดสรรโดยผู้เชี่ยวชาญ">เครื่องมือออกแบบเว็บสำหรับมืออาชีพ: คัดสรรโดยผู้เชี่ยวชาญ</p>
                            </a>
                        </div>
                    </li>

                </ol>
            </section>
        </section>
        <aside class="box-r">
            <section class="box4-1">
                <strong>Python</strong>
                <ol>

                    <li class="f-start">
                        <i><img loading='lazy' src="https://th.wsxdn.com/css/img/article-lan.svg" alt=""></i>
                        <a href="https://th.wsxdn.com/db044w/wu448o/1004103141.html" title="ตรวจสอบว่า Tuple มีแค่ค่า None ใน Python">
                            <p class="r-over r-over-2">ตรวจสอบว่า Tuple มีแค่ค่า None ใน Python</p>
                        </a>
                    </li>

                    <li class="f-start">
                        <i><img loading='lazy' src="https://th.wsxdn.com/css/img/article-lan.svg" alt=""></i>
                        <a href="https://th.wsxdn.com/db044w/wu448o/1004105935.html" title="การดึงข้อมูลเว็บ (Web Scraping) ด้วย Scrapy ใน Python">
                            <p class="r-over r-over-2">การดึงข้อมูลเว็บ (Web Scraping) ด้วย Scrapy ใน Python</p>
                        </a>
                    </li>

                    <li class="f-start">
                        <i><img loading='lazy' src="https://th.wsxdn.com/css/img/article-lan.svg" alt=""></i>
                        <a href="https://th.wsxdn.com/db044w/wu448o/1004105955.html" title="การนำ Web Scraping ไปใช้งานใน Python ด้วย Scrapy">
                            <p class="r-over r-over-2">การนำ Web Scraping ไปใช้งานใน Python ด้วย Scrapy</p>
                        </a>
                    </li>

                    <li class="f-start">
                        <i><img loading='lazy' src="https://th.wsxdn.com/css/img/article-lan.svg" alt=""></i>
                        <a href="https://th.wsxdn.com/db044w/wu448o/1004106157.html" title="Web Scraping ใน Python ด้วย BeautifulSoup (bs4)">
                            <p class="r-over r-over-2">Web Scraping ใน Python ด้วย BeautifulSoup (bs4)</p>
                        </a>
                    </li>

                    <li class="f-start">
                        <i><img loading='lazy' src="https://th.wsxdn.com/css/img/article-lan.svg" alt=""></i>
                        <a href="https://th.wsxdn.com/db044w/wu448o/1004106231.html" title="โมดูล Newspaper สำหรับดึงข้อมูลและจัดการบทความจากเว็บไซต์ข่าว">
                            <p class="r-over r-over-2">โมดูล Newspaper สำหรับดึงข้อมูลและจัดการบทความจากเว็บไซต์ข่าว</p>
                        </a>
                    </li>

                </ol>
            </section>
            <ul>

                <li class="f-start f-align">
                    <a href="https://th.wsxdn.com/db044w/wu448o/1004105784.html" class="i-text"><p class="r-over r-over-3">โปรแกรม Python สำหรับ Cocktail Sort</p></a>
                </li>

                <li class="f-start f-align">
                    <a href="https://th.wsxdn.com/db044w/wu448o/1004105788.html" class="i-text"><p class="r-over r-over-3">โปรแกรม Python สำหรับ Anagram Substring Search (การค้นหาย่อหน้า Anagram)</p></a>
                </li>

                <li class="f-start f-align">
                    <a href="https://th.wsxdn.com/db044w/wu448o/1004105925.html" class="i-text"><p class="r-over r-over-3">โปรแกรม Python ตรวจสอบว่าจำนวนตัวหาร (Divisors) เป็นคี่หรือคู่</p></a>
                </li>

                <li class="f-start f-align">
                    <a href="https://th.wsxdn.com/db044w/wu448o/1004105934.html" class="i-text"><p class="r-over r-over-3">การดึงข้อมูลเว็บ (Web Scraping) ด้วย lxml ใน Python</p></a>
                </li>

                <li class="f-start f-align">
                    <a href="https://th.wsxdn.com/db044w/wu448o/1004105954.html" class="i-text"><p class="r-over r-over-3">การนำ Web Scraping ไปใช้งานด้วย lxml ใน Python Programming</p></a>
                </li>

            </ul>
            <ul class="types f-between">
                <li><a class='childclass' href='https://th.wsxdn.com/db044w/hf444z/' target="_self">การเขียนโปรแกรม C</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/bz445u/' target="_self">C++</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/tr446l/' target="_self">Redis</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/rp447j/' target="_self">การเขียนโปรแกรม Bash</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/wu448o/' target="_self">Python</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/nl449f/' target="_self">Java</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/ig450a/' target="_self">ฐานข้อมูล</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/zx451s/' target="_self">HTML</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/ec452w/' target="_self">JavaScript</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/db453v/' target="_self">การเขียนโปรแกรม</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/if454a/' target="_self">CSS</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/ge455y/' target="_self">Ruby</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/xv456p/' target="_self">SQL</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/jh457b/' target="_self">iOS</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/om458g/' target="_self">Android</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/mk459f/' target="_self">MongoDB</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/rp460j/' target="_self">MySQL</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/qn461i/' target="_self">C#</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/jh465b/' target="_self">PHP</a></li>
<li><a class='childclass' href='https://th.wsxdn.com/db044w/kh471c/' target="_self">SQL Server</a></li>
            </ul>
        </aside>
    </section>
    <footer>
        <section class="msg f-center container">
            <span class="f-start">
                ลิขสิทธิ์ ©
                <a href="https://th.wsxdn.com">https://th.wsxdn.com</a>
                สงวนลิขสิทธิ์
            </span>
        </section>
    </footer>
</body>
</html>