91tv成人-91TV成人版-91tv成人短视频-91TV看片-91tv日韩-91tv在线福利-91tv在线福利观看-91video-91v天堂在线观看-91www

Python網(wǎng)絡(luò)爬蟲實戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

首頁 > 產(chǎn)品大全 > Python網(wǎng)絡(luò)爬蟲實戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

Python網(wǎng)絡(luò)爬蟲實戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

Python網(wǎng)絡(luò)爬蟲實戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

網(wǎng)絡(luò)爬蟲是獲取互聯(lián)網(wǎng)數(shù)據(jù)的重要工具,Python因其豐富的庫和簡潔的語法成為爬蟲開發(fā)的首選語言。在眾多爬蟲工具中,Scrapy和Beautiful Soup各具特色,結(jié)合使用能高效完成數(shù)據(jù)采集與處理任務(wù)。

一、Scrapy框架的使用

Scrapy是一個功能強大的爬蟲框架,適合大規(guī)模、結(jié)構(gòu)化的數(shù)據(jù)采集。

1. 基礎(chǔ)架構(gòu)

  • 引擎(Engine):控制數(shù)據(jù)流,協(xié)調(diào)各組件工作
  • 調(diào)度器(Scheduler):管理請求隊列
  • 下載器(Downloader):獲取網(wǎng)頁內(nèi)容
  • 爬蟲(Spider):定義爬取邏輯和數(shù)據(jù)提取規(guī)則
  • 項目管道(Pipeline):處理提取的數(shù)據(jù)

2. 快速入門

`python import scrapy

class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['http://example.com']

def parse(self, response):
# 提取數(shù)據(jù)

title = response.css('h1::text').get()
yield {'title': title}

# 跟進鏈接

for link in response.css('a::attr(href)').getall():
yield response.follow(link, self.parse)
`

3. 高級特性

  • 中間件:自定義請求/響應(yīng)處理
  • Item Loader:結(jié)構(gòu)化數(shù)據(jù)提取
  • Feed導(dǎo)出:支持JSON、CSV等多種格式
  • 去重過濾:自動避免重復(fù)爬取

二、Beautiful Soup的使用

Beautiful Soup是靈活的HTML/XML解析庫,適合小規(guī)模或結(jié)構(gòu)不規(guī)則的頁面。

1. 基礎(chǔ)解析

`python from bs4 import BeautifulSoup import requests

html = requests.get('http://example.com').text
soup = BeautifulSoup(html, 'lxml')

多種選擇器

soup.find('div', class='content')
soup.select('div.content > p')
soup.find
all(text='特定文本')
`

2. 解析器選擇

  • lxml:速度快,容錯性好(推薦)
  • html.parser:Python內(nèi)置,無需額外安裝
  • html5lib:容錯性最好,速度較慢

三、數(shù)據(jù)處理技巧

1. 數(shù)據(jù)清洗

`python import re from datetime import datetime

去除空白字符

def clean_text(text):
return re.sub(r'\s+', ' ', text).strip()

日期標(biāo)準(zhǔn)化

def normalizedate(datestr):
formats = ['%Y-%m-%d', '%d/%m/%Y', '%b %d, %Y']
for fmt in formats:
try:
return datetime.strptime(date_str, fmt).date()
except:
continue
return None
`

2. 數(shù)據(jù)驗證

`python import pandas as pd from cerberus import Validator

schema = {
'title': {'type': 'string', 'required': True},
'price': {'type': 'float', 'min': 0},
'url': {'type': 'string', 'regex': '^https?://'}
}

validator = Validator(schema)
if validator.validate(data):
# 數(shù)據(jù)有效

pass
`

3. 數(shù)據(jù)存儲

`python # 存儲到CSV

import csv
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data_list)

存儲到數(shù)據(jù)庫

import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS items
(title TEXT, price REAL, url TEXT)''')
`

四、數(shù)據(jù)處理服務(wù)設(shè)計

1. 服務(wù)架構(gòu)

數(shù)據(jù)采集層(Scrapy/Requests) → 數(shù)據(jù)解析層(Beautiful Soup) →
數(shù)據(jù)處理層(清洗/驗證) → 數(shù)據(jù)存儲層(數(shù)據(jù)庫/文件) →
數(shù)據(jù)API層(RESTful接口)

2. 錯誤處理機制

  • 網(wǎng)絡(luò)請求重試
  • 解析失敗日志記錄
  • 數(shù)據(jù)質(zhì)量監(jiān)控
  • 異常數(shù)據(jù)隔離

3. 性能優(yōu)化

`python # 使用aiohttp異步請求

import aiohttp
import asyncio

async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()

使用線程池

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(maxworkers=10) as executor:
results = executor.map(process
data, data_list)
`

五、最佳實踐建議

  1. 遵守robots.txt:尊重網(wǎng)站爬取規(guī)則
  2. 設(shè)置合理延遲:避免對目標(biāo)網(wǎng)站造成壓力
  3. 使用User-Agent:模擬真實瀏覽器訪問
  4. 處理反爬機制:合理使用代理IP和Cookie
  5. 數(shù)據(jù)去重:避免存儲重復(fù)數(shù)據(jù)
  6. 定期維護:更新選擇器,適應(yīng)網(wǎng)站改版

六、完整示例:電商價格監(jiān)控系統(tǒng)

`python import scrapy from bs4 import BeautifulSoup import pandas as pd from datetime import datetime

class PriceMonitorSpider(scrapy.Spider):
name = 'pricemonitor'

def start
requests(self):
urls = ['http://example.com/products']
for url in urls:
yield scrapy.Request(url, callback=self.parselist)

def parse
list(self, response):
soup = BeautifulSoup(response.text, 'lxml')
products = soup.select('.product-item')

for product in products:
item = {
'name': product.selectone('.name').text.strip(),
'price': float(product.select
one('.price').text.replace('¥', '')),
'url': response.urljoin(product.selectone('a')['href']),
'crawl
time': datetime.now().isoformat()
}
yield item

# 在settings.py中配置數(shù)據(jù)管道

ITEM_PIPELINES = {

'project.pipelines.DataCleanPipeline': 300,

'project.pipelines.DatabasePipeline': 800,

}

`

七、

Scrapy和Beautiful Soup是Python爬蟲生態(tài)中的黃金組合。Scrapy適合構(gòu)建完整的爬蟲項目,提供完整的框架支持;Beautiful Soup則在小規(guī)模、快速開發(fā)的場景中表現(xiàn)出色。結(jié)合兩者的優(yōu)勢,配合合理的數(shù)據(jù)處理流程,可以構(gòu)建出高效、穩(wěn)定的數(shù)據(jù)采集與處理服務(wù)。

在實際開發(fā)中,應(yīng)根據(jù)具體需求選擇合適工具,注重代碼的可維護性和擴展性,同時遵守相關(guān)法律法規(guī)和網(wǎng)站使用條款,實現(xiàn)可持續(xù)的數(shù)據(jù)采集服務(wù)。

如若轉(zhuǎn)載,請注明出處:http://m.jzzjfy.cn/product/25.html

更新時間:2026-06-19 04:03:31

主站蜘蛛池模板: 老男人av | 国产乱理伦片在线 | 青草青青国产AⅤ | 高清不卡一卡二卡 | 欧洲影院 | 日韩全黄频 | 成年人看片网站 | 欧美xxx在线| 91精品午夜网站 | 成人影视一区二区 | 免费看小黄片网站 | 超碰人妻自拍豆花 | 国产在线综合网 | 日韩伦理免费电影 | 欧美一卡视频 | 日韩在线视频免费 | 成人高清在线观看 | 国产啪亚洲国产 | 91网红在线观看 | 国产亚洲人成 | 欧美浮力地 | 小草免费视频播放 | 在线网址无吗 | 国产资源视频吃瓜 | 五月天综合影院 | 福利在线免费观看 | 日本一级电影 | 91丝袜视频 | 高清完整版 | 91操喷| 91热视频 | 无码四虎| 亚洲视频成人 | 午夜成年影院 | 91短视频在线看 | 欧美亚洲视频 | 青青操嫩逼 | 91网在线观看0 | 欧美亚洲国产视频 | 国产精品免费 | 国产在线观看资源 |