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

Công cụ Web Scraping trong Python

Web scraping: trích xuất dữ liệu từ web, chuyển phi cấu trúc thành có cấu trúc. 6 thư viện phổ biến.

So sánh nhanh

Thư việnLoạiJS SupportĐộ phức tạpDùng cho
urllibBuilt-in HTTPKhôngThấpRequest đơn giản
requestsHTTP clientKhôngThấpAPI, REST, HTML tĩnh
BeautifulSoupParser HTMLKhôngTrung bìnhParse, extract DOM
lxmlParser XML/HTMLKhôngTrung bìnhTốc độ cao, XPath
SeleniumBrowser automationCóCaoSPA, dynamic JS, test
MechanicalSoupStateful browserKhôngTrung bìnhForm, login, redirect

1. urllib (stdlib)

from urllib.request import urlopen
html = urlopen("https://www.tutorialspoint.com/").read()
print(html[:500])

2. Requests (khuyên dùng cho HTTP)

import requests
r = requests.get('https://www.tutorialspoint.com/')
print(r.status_code)      # 200
print(r.encoding)         # UTF-8
print(r.headers['Content-Type'])
print(r.url)
print(r.elapsed)

3. BeautifulSoup (parse HTML)

from bs4 import BeautifulSoup
import requests

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

for link in soup.find_all('a'):
    print(link.get('href'))

4. lxml (parser nhanh, XPath)

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())
# <body/></html></code></pre>

<h2>5. Selenium (JavaScript rendering)</h2>
<pre class="prettyprint notranslate"><code>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>

<h2>6. MechanicalSoup (form, session)</h2>
<pre class="prettyprint notranslate"><code>import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("https://www.tutorialspoint.com/")
browser.follow_link("forms")
print(browser.get_url())</code></pre>

<h2>Khuyên dùng</h2>
<ul>
<li>HTML tĩnh + API: <strong>requests + BeautifulSoup/lxml</strong>.</li>
<li>Cần JS, SPA, click, scroll: <strong>Selenium/Playwright</strong>.</li>
<li>Login, form, session: <strong>MechanicalSoup/requests.Session</strong>.</li>
<li>Tuân thủ <code>robots.txt</code>, rate limit, terms of service.</li>
</ul>
                </article>
                <div class="ad5">
<script language='javascript' src='/ad/w.js'></script>
                </div>
            </section>
            <div id="turn-page" class="f-between">
                <div class="page up f-align">
                    <i class="prev"></i>
                    <section>
                        <a class='LinkPrevArticle' href='https://vn.wsxdn.com/fd034x/ur348m/1003106443.html' >Đọc ghi file Excel với openpyxl trong Python</a> 
                    </section>
                </div>
                <div class="page down f-align">
                    <section>
                        <a class='LinkNextArticle' href='https://vn.wsxdn.com/fd034x/ur348m/1003106445.html'  >Game Kéo Búa Bao (Rock Paper Scissors) Python</a> 
                    </section>
                    <i class="next"></i>
                </div>
             </div>
             <section class="box4-l-list">
                <div class="imgList f-between banner">
                    <ul class="f-between">

<li class="f-between f-align"><div>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105954.html" class="text r-over r-over-3" title="Triển khai Web Scraping sử dụng lxml trong lập trình Python">Triển khai Web Scraping sử dụng lxml trong lập trình Python</a>
</div></li>

<li class="f-between f-align"><div>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003106241.html" class="text r-over r-over-3" title="Web Scraping (Cào dữ liệu web) bằng Python và Scrapy">Web Scraping (Cào dữ liệu web) bằng Python và Scrapy</a>
</div></li>

<li class="f-between f-align"><div>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003106255.html" class="text r-over r-over-3" title="Thu thập dữ liệu web với lxml trong Python">Thu thập dữ liệu web với lxml trong Python</a>
</div></li>

<li class="f-between f-align"><div>
<a href="https://vn.wsxdn.com/yw036q/nl343f/1003136961.html" class="text r-over r-over-3" title="31 Công cụ Web Scraping tốt nhất 2024 – Dễ dùng, Mạnh mẽ, Tin cậy cho mọi người">31 Công cụ Web Scraping tốt nhất 2024 – Dễ dùng, Mạnh mẽ, Tin cậy cho mọi người</a>
</div></li>

<li class="f-between f-align"><div>
<a href="https://vn.wsxdn.com/ec031w/zx314s/1003148987.html" class="text r-over r-over-3" title="Các công cụ thiết kế web chuyên nghiệp hàng đầu: Lựa chọn của chuyên gia">Các công cụ thiết kế web chuyên nghiệp hàng đầu: Lựa chọn của chuyên gia</a>
</div></li>

                    </ul>
                </div>
            </section>
        </section>
        <aside class="box-r box4-r">
            <div class="articleList">
                <em>Bài báo nổi tiếng</em>
                <ol>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003103141.html" class="t-over" title="Kiểm tra tuple toàn giá trị None trong Python">Kiểm tra tuple toàn giá trị None trong Python</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003105425.html" class="t-over" title="CGI là gì trong Python?">CGI là gì trong Python?</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003105762.html" class="t-over" title="Chương trình Python Stooge Sort">Chương trình Python Stooge Sort</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003105763.html" class="t-over" title="Chương trình Python Sieve of Eratosthenes (Sàng Eratosthenes)">Chương trình Python Sieve of Eratosthenes (Sàng Eratosthenes)</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003105935.html" class="t-over" title="Triển khai Web Scraping với Scrapy trong Python">Triển khai Web Scraping với Scrapy trong Python</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003105955.html" class="t-over" title="Triển khai Web Scraping trong Python với Scrapy">Triển khai Web Scraping trong Python với Scrapy</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003106157.html" class="t-over" title="Web Scraping Python với BeautifulSoup">Web Scraping Python với BeautifulSoup</a></li>

<li><a href="https://vn.wsxdn.com/fd034x/ur348m/1003106231.html" class="t-over" title="Module Newspaper của Python cho cài đặt và tuyển tập bài báo">Module Newspaper của Python cho cài đặt và tuyển tập bài báo</a></li>

</ol>
            </div>
            <section>
                <strong class="list-title">
                    <p>Hướng Dẫn Máy Tính</p>
                    <span></span>
                </strong>
                <ol class="texts">

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105766.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python QuickSort</strong></a>
</li>

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105770.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python Merge Sort</strong></a>
</li>

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105774.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python Heap Sort</strong></a>
</li>

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105781.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python bài toán cắt thanh (Cutting a Rod)</strong></a>
</li>

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105783.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python bài toán đổi tiền (Coin Change)</strong></a>
</li>

<li>
<a href="https://vn.wsxdn.com/fd034x/ur348m/1003105784.html" class="t-title"><strong class="r-over r-over-2">Chương trình Python Cocktail Sort</strong></a>
</li>

</ol>
</section>
            <ul class="typeList container f-start box4-typeList">
                <li><a class='childclass' href='https://vn.wsxdn.com/fd034x/sq344k/' target="_self">Lập Trình C</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ay345t/' target="_self">C++</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/zx346r/' target="_self">Redis</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/nk347f/' target="_self">Lập Trình Bash</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ur348m/' target="_self">Python</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ca349u/' target="_self">Java</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/hf350z/' target="_self">Cơ Sở Dữ Liệu</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/om351g/' target="_self">HTML</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/tr352l/' target="_self">JavaScript</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ay353s/' target="_self">Lập Trình</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/jg354b/' target="_self">CSS</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/nl355g/' target="_self">Ruby</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/mk356e/' target="_self">SQL</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ge357z/' target="_self">iOS</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ec358x/' target="_self">Android</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/ol359g/' target="_self">MongoDB</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/vt360n/' target="_self">MySQL</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/vt361n/' target="_self">C#</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/wu365o/' target="_self">PHP</a></li>
<li><a class='childclass' href='https://vn.wsxdn.com/fd034x/us371m/' target="_self">SQL Server</a></li>
            </ul>
        </aside>
    </section>
    <footer class="container">
        <span class="container f-center">
                Bản quyền ©
                <a href="https://vn.wsxdn.com">https://vn.wsxdn.com</a>
                Đã đăng ký Bản quyền
            </span>

    </footer>
</body>
</html>