Prompt Title: 蝦皮商品銷量爬蟲

Created 1 year ago
Votes 0
Views 172 times
0

Prompt Detail:

以下是使用 Python 和 BeautifulSoup 套件來撰寫一個能夠讀取 CSV 檔案,抓取每個商品的歷史銷量並輸出成新的 CSV 檔案的程式碼:

python
import csv import requests from bs4 import BeautifulSoup # 載入 CSV 檔案 with open('urls.csv', 'r') as file: reader = csv.reader(file) # 迴圈讀取每一列 for row in reader: url = row[0] # 發送 GET 請求 response = requests.get(url) # 解析 HTML soup = BeautifulSoup(response.text, 'html.parser') # 獲取商品名稱 product_name = soup.find('h1', {'class': 'qaNIZv'}).text.strip() # 獲取商品歷史銷量 sales = soup.find('div', {'class': 'dQm2af'}).text.strip() # 將商品名稱和歷史銷量寫入 CSV 檔案 with open('sales.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow([product_name, sales])

程式碼中,我們首先使用 csv 模組來讀取 CSV 檔案,然後使用 requests 套件發送 GET 請求,獲取網頁內容。接著,使用 BeautifulSoup 套件解析 HTML,獲取商品名稱和歷史銷量,最後將結果寫入一個新的 CSV 檔案中。

需要注意的是,在這個程式中,我們使用了 a 參數來打開 CSV 檔案,這表示我們希望以「追加」的方式寫入新的資料,而非覆蓋舊有的內容。如果你想要清空舊有內容,可以先使用 w 參數打開檔案,然後在迴圈之前先寫入 CSV 的標題欄位。

avatar
Steven
Shared 4 prompts
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
Steel Pricing Regression Model
1 year ago 2023-03-11 16:33:33 Bobby
0
0
WP Blog Migration
1 year ago 2023-03-14 18:42:05 Evert
0
0
Python QA
1 year ago 2023-03-15 04:15:01 Chittibabu
0
0
0
0
Python Interpreter
1 year ago 2023-03-19 21:23:14 Ruben Chapa
0
0
Python Telegram Bot.
1 year ago 2023-03-26 11:49:32 stew
0
0
Python代码识别正方形
1 year ago 2023-03-28 12:57:13 Jobs
0
0
Convert string to Date
1 year ago 2023-03-31 11:32:28 Suman
0
0
Twitter unfollow script.
1 year ago 2023-04-01 21:49:09 Victor Ventura
0
0
Python Exception Handling
1 year ago 2023-04-10 21:04:13 Krzysztof
0
0
Upload art to OpenAI.
1 year ago 2023-04-15 13:26:10 Shangz
0
0
PostgreSQL 트리거 생성.
1 year ago 2023-04-28 04:35:23 mglife
0
0
Coding
1 year ago 2023-04-29 04:27:18 RAGHAV S
0
0
PyTorch: GPU not available.
1 year ago 2023-04-29 14:52:33 Excido
0
0
Python-R 모델 호출
1 year ago 2023-05-05 02:56:18 Lucy
0
0
python flask program REST api
11 months ago 2023-05-13 09:04:20 rohit
0
0
Remove named entities
7 months ago 2023-09-22 11:36:27 Ilyos
0
0
example
1 month ago 2024-03-13 07:10:22 Uriel