from crawlee.playwright_crawler import PlaywrightCrawler, PlaywrightCrawlingContext

async def main() -> None:
# Create a crawler instance
crawler = PlaywrightCrawler(
# headless=False,
# browser_type='firefox',
)

@crawler.router.default_handler
async def request_handler(context: PlaywrightCrawlingContext) -> None:
data = {
"request_url": context.request.url,
"page_url": context.page.url,
"page_title": await context.page.title(),
"page_content": (await context.page.content())[:10000],
}
await context.push_data(data)

await crawler.run(["https://crawlee.dev"])

if __name__ == "__main__":
asyncio.run(main())

使用Crawlee的PlaywrightCrawler抓取網站標題及內容示例

2.Requests

每個網絡抓取任務的首要步驟都是向目標網站發送請求并獲取其內容,這些內容通常為HTML格式。Python中的Requests庫正是為此而生,它憑借“HTTP for humans”的核心理念,極大地簡化了這一過程,因此成為了下載次數最多的Python包。

? 特征

?? 優點

?? 缺點

?? 選擇

httpx, urlib3, http.client, aiohttp

?? 安裝請求

要安裝 Requests 庫,請使用 Python 包管理器 pip:

pip install requests

?? 代碼示例

import requests

response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json() # Parse JSON response
print(data)
else:
print(f"Request failed with status code: {response.status_code}")

3. HTTPX

HTTPX 作為新一代 HTTP 庫,相較于 Requests,提供了異步和 HTTP/2 等高級功能。如異步和 HTTP/2 支持。HTTPX 在核心功能與 Requests 保持高度一致,易于上手。鑒于其高性能與良好的擴展性,HTTPX 不僅適用于大型項目,也推薦用于小型項目,為未來可能的需求擴展預留空間。

? 特征

?? 優點

?? 缺點

?? 選擇

Requests, aiohttp, urlib3, http.client

?? 安裝 HTTPX

要安裝 HTTPX 庫,請使用 Python 包管理器 pip:

pip install httpx

?? 代碼示例

import httpx
import asyncio

async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json() # Parse JSON response
print(data)
else:
print(f"Request failed with status code: {response.status_code}")

# Run the asynchronous function
asyncio.run(fetch_data())

4. Beautiful Soup

一旦你擁有 HTML 內容,你需要一種方法去解析它并提取你感興趣的數據。為此,Beautiful Soup這一流行的Python HTML解析器應運而生。它允許你在HTML樹結構中輕松導航和搜索,從而獲取你感興趣的數據。其簡單的語法和簡單的設置也使 Beautiful Soup 成為中小型 Web 抓取項目和 Web 抓取初學者的絕佳選擇。

? 特征

?? 優點

?? 缺點

?? 選擇

lxml、html5lib

?? 安裝 Beautiful Soup

為了安裝Beautiful Soup,請使用pip來安裝相應的軟件包。此外,為了獲得更佳的解析功能,我們還建議安裝lxml或html5lib。這些庫與beautifulsoup4配合使用,能夠顯著提升HTML內容的解析效果。

pip install beautifulsoup4 lxml

?? 代碼示例

from bs4 import BeautifulSoup
import httpx

# Send an HTTP GET request to the specified URL using the httpx library
response = httpx.get("https://news.ycombinator.com/news")

# Save the content of the response
yc_web_page = response.content

# Use the BeautifulSoup library to parse the HTML content of the webpage
soup = BeautifulSoup(yc_web_page)

# Find all elements with the class "athing" (which represent articles on Hacker News) using the parsed HTML
articles = soup.find_all(class_="athing")

# Loop through each article and extract relevant data, such as the URL, title, and rank
for article in articles:
data = {
"URL": article.find(class_="titleline").find("a").get('href'), # Find the URL of the article by finding the first "a" tag within the element with class "titleline"
"title": article.find(class_="titleline").getText(), # Find the title of the article by getting the text content of the element with class "titleline"
"rank": article.find(class_="rank").getText().replace(".", "") # Find the rank of the article by getting the text content of the element with class "rank" and removing the period character
}
# Print the extracted data for the current article
print(data)

5.  Mechanical Soup

Mechanical Soup 是一個 Python 庫,它提供了Requests和BeautifulSoup庫的更高級別抽象。它通過將 Requests 的易用性與 Beautiful Soup 的 HTML 解析功能相結合,簡化了 Web 抓取過程。

? 特征

?? 優點

?? 缺點

?? 選擇

Selenium, Playwright, Beautiful Soup

?? 安裝 Mechanical Soup

要安裝 MechanicalSoup,請在終端或命令提示符中運行以下命令:

pip install MechanicalSoup

?? 代碼示例

import mechanicalsoup

# Create a MechanicalSoup browser instance
browser = mechanicalsoup.StatefulBrowser()

# Perform a GET request to a webpage
browser.open("https://example.com")

# Extract data using BeautifulSoup methods
page_title = browser.get_current_page().title.text

print("Page Title:", page_title)

6. Selenium

Selenium 是一種廣泛使用的 Web 自動化工具,它允許開發人員以編程方式與 Web 瀏覽器交互。通常用于測試 Web 應用程序,但它也可以作為 Web 抓取的強大工具,尤其是在處理需要動態內容加載的 JavaScript 渲染的網站時。

? 特征

?? 優點

?? 缺點

?? 選擇

Playwright, Mechanical Soup, Crawlee, Scrapy

?? 安裝 Selenium

要安裝 Selenium,請在終端或命令提示符中運行以下命令:

pip install selenium

?? 代碼示例

from selenium import webdriver

# Setup the WebDriver (using Chrome in this example)
driver = webdriver.Chrome()

# Navigate to a web page
driver.get("https://example.com")

# Interact with the page (e.g., click a button)
button = driver.find_element_by_id("submit")
button.click()

# Extract data
content = driver.page_source

# Close the browser
driver.quit()

7. Playwright

Playwright 是由 Microsoft 開發的現代 Web 自動化框架。它憑借單個API支持多個瀏覽器(包括Chromium、Firefox和WebKit),提供了與網頁交互的強大功能。Playwright因其出色的速度、可靠性和處理復雜Web應用程序的能力,在測試和自動化領域備受青睞。與Selenium相似,在處理需要動態內容加載的網站時,Playwright也是一個強大的網絡抓取工具。

? 特征

?? 優點

?? 缺點

?? 選擇

Selenium, Crawlee, Scrapy

?? 安裝 Playwright

要安裝 Playwright,請在終端或命令提示符中運行以下命令:

pip install playwright

然后,您需要安裝必要的瀏覽器二進制文件:

playwright install

?? 代碼示例

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")

# Interact with the page
page.click('button#submit')

# Extract data
content = page.content()

browser.close()

8. Scrapy

Scrapy是一個功能強大且高度靈活的Python框架,專門用于網絡抓取。與常用于Web自動化的Selenium和Playwright不同,Scrapy的設計目標是以結構化和可擴展的方式從網站抓取大量數據。

? 特征

?? 優點

?? 缺點

?? 選擇

Crawlee, Beautiful Soup, Selenium, Playwright

?? 安裝 Scrapy

要安裝 Scrapy,請在您的終端或命令提示符中運行以下命令:

pip install scrapy

?? 代碼示例

import scrapy

class HackernewsSpiderSpider(scrapy.Spider):
name = 'hackernews_spider'
allowed_domains = ['news.ycombinator.com']
start_urls = ['http://news.ycombinator.com/']

def parse(self, response):
articles = response.css('tr.athing')
for article in articles:
yield {
"URL": article.css(".titleline a::attr(href)").get(),
"title": article.css(".titleline a::text").get(),
"rank": article.css(".rank::text").get().replace(".", "")
}

哪個 Python 抓取庫適合您?

那么,在選擇網絡抓取項目的庫時,您應該考慮哪些選項呢?以下表格總結了本文介紹的所有庫的功能特性、主要用途、顯著優點及潛在缺點:

圖書館用例易用性特征優點缺點選擇
Crawlee大規模抓取和瀏覽器自動化簡單自動并行爬取、代理輪換、持久隊列易于設置、干凈的代碼、集成功能新的有限教程Scrapy, Playwright, Beautiful Soup
Requests發出 HTTP 請求非常簡單簡單的 API、SSL/TLS 支持、流媒體大型社區,有據可查沒有異步,對于性能敏感型任務來說速度較慢httpx, urllib3, aiohttp
HTTPX支持異步的 HTTP 請求簡單異步支持、HTTP/2、可自定義傳輸非阻塞請求,現代標準學習強度更大,社區規模更小Requests, aiohttp, urllib3
Beautiful SoupHTML/XML 解析非常簡單樹遍歷、編碼處理、多解析器支持語法簡單,非常適合初學者可擴展性有限,不支持 JavaScriptlxml, html5lib
Mechanical Soup表單處理、簡單的網頁抓取簡單請求 + Beautiful Soup 集成,表單提交簡化的界面、會話處理有限的高級功能Selenium, Playwright
Selenium瀏覽器自動化、JavaScript 密集型網站中等跨瀏覽器的動態內容處理模擬復雜的交互,多語言支持速度較慢,資源密集Playwright, Crawlee, Scrapy
Playwright高級瀏覽器自動化中等多瀏覽器支持、自動等待、并行執行處理 JS 密集型網站、高級功能學習強度更大,社區更小Selenium, Crawlee, Scrapy
Scrapy大規模 Web 抓取異步、分布式抓取、可擴展性高效,處理復雜場景學習強度更大,設置繁重Crawlee, Playwright, Selenium

此處介紹的每種工具在專家抓取工具的工具包中都有其獨特的用途。根據任務需求掌握它們的使用,將賦予您靈活選擇最佳工具的能力,因此,在做出決定前,不妨大膽嘗試每一種工具!

原文鏈接:https://blog.apify.com/what-are-the-best-python-web-scraping-libraries/

上一篇:

2023年頂級編程語言:企業的技術趨勢

下一篇:

每個開發人員都應該知道的10個JAVASCRIPT SEO技巧
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費