電商數據分析是個香餑餑,可市面上的數據采集工具要不貴得嚇人,要不就是各種廣告彈窗。干脆自己動手寫個爬蟲,想抓啥抓啥,還能學點技術。今天咱聊聊怎么用Python寫個簡單的電商數據爬蟲。
打好基礎:搞定請求頭
別看爬蟲很牛,但基礎工作得做足。瀏覽器訪問網頁時會帶上各種?請求頭信息?,咱們寫爬蟲也得模仿這個行為,不然分分鐘被網站攔截。
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5',
}
溫馨提示:每個網站的反爬策略不一樣,有時候可能需要加上Cookie、Referer等信息。要是遇到了再加就成。
發起請求:requests庫來幫忙
發請求用?requests庫?準沒錯,簡單好用還穩定。pip安裝一下就能用:
import requests
def get_page(url):
try:
response = requests.get(url, headers=headers, timeout=5)
return response.text
except Exception as e:
print(f'哎呀,出錯了:{e}')
return None
解析數據:BeautifulSoup大顯神通
拿到網頁內容后,就該解析數據了。?BeautifulSoup?是個好幫手,把亂糟糟的HTML轉成結構化的數據:
from bs4 import BeautifulSoup
def parse_product(html):
if not html:
return []
soup = BeautifulSoup(html, 'html.parser')
products = []
items = soup.find_all('div', class_='item') # 具體class名要看網站結構
for item in items:
product = {
'title': item.find('div', class_='title').text.strip(),
'price': item.find('span', class_='price').text.strip(),
'sales': item.find('span', class_='sales').text.strip()
}
products.append(product)
return products
存儲數據:pandas幫你整理
數據爬下來了,得好好存起來。用?pandas?轉成Excel,分析起來賊方便:
import pandas as pd
def save_data(products):
df = pd.DataFrame(products)
df.to_excel('products.xlsx', index=False)
print(f'搞定!共保存了{len(products)}條數據')
完整代碼:整合一下
把上面的代碼整合一下,就能一鍵采集數據了:
def main():
base_url = 'https://example.com/products?page={}' # 替換成實際的網站
all_products = []
for page in range(1, 6): # 采集5頁數據
url = base_url.format(page)
print(f'正在爬取第{page}頁...')
html = get_page(url)
products = parse_product(html)
all_products.extend(products)
time.sleep(1) # 別爬太快,對別人服務器好點
save_data(all_products)
if __name__ == '__main__':
main()
溫馨提示:記得改成你要爬的網站地址,不同網站的HTML結構不一樣,解析規則也得相應調整。
反爬處理:多動點小腦筋
網站肯定不愿意讓你隨便爬數據,咱得講究點技巧:
-
IP代理池:換著IP訪問,降低被封風險
-
隨機延時:別一直用固定間隔,顯得太機械
-
隨機UA:多準備幾個User-Agent輪著用
-
驗證碼處理:遇到驗證碼可以用OCR識別
這個爬蟲還挺實用,不光能爬電商數據,改改解析規則,啥數據都能爬。寫爬蟲最重要的是要有耐心,遇到問題別著急,慢慢調試就成。代碼寫好了,運行起來那叫一個爽,分分鐘幾千條數據到手。