T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 92 天:亚马逊爬虫:翻页、解析与存 CSV

这是「Python 100 天」系列第 92 天的学习笔记:亚马逊爬虫:翻页、解析与存 CSV。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

输入一个关键词,爬亚马逊加拿大站前 7 页搜索结果,抓出:商品名、原价、现价、折扣百分比、评分、评论数、链接,存成 CSV。README 知识点:BeautifulSoup 选择元素、Selenium 选择元素、用两者抓真实网站数据。

一、为什么要用 Selenium 拿 HTML

1
2
driver.get(url.format(page))
soup = BeautifulSoup(driver.page_source, 'html.parser')

亚马逊的搜索结果大部分是服务端渲染的,理论上 requests.get 就能拿到。但:

  • 它有很强的反爬(User-Agent、Cookie、验证码);
  • 有些区块是 JS 动态插入的。

Selenium 的真实浏览器环境能绕过一部分检测,代价是慢 10 倍、吃内存。

最佳实践是"用 Selenium 拿 page_source,交给 BeautifulSoup 解析"——这份代码正是这么做的:浏览器负责"拿到完整 HTML",BS4 负责"快速提取"。

二、URL 构造与翻页

1
2
3
4
5
6
7
8
9
def get_url(search_term):
template = 'https://www.amazon.ca/s?k={}'
search_term = search_term.replace(' ', '+')
url = template.format(search_term)
url += '&page={}' # 留一个占位符给页码
return url

for page in range(1, 8):
driver.get(url.format(page))

两级 format:第一层填关键词,第二层填页码。' ' → '+' 是查询串的空格编码。

range(1, 8) = 第 1–7 页。

三、找"商品卡片"这个容器

1
results = soup.find_all('div', {'data-component-type': 's-search-result'})

先找到"每个商品的外层 div",再在里面找具体字段。这个 data-component-type 属性比 class 稳定得多(亚马逊的 class 名带哈希,如 s-result-item s-asin sg-col-0-of-12,随时会变)。

这是爬虫的核心策略:优先用 data-*、id、语义属性,最后才用 class。

四、嵌套 try:字段缺失是常态

1
2
3
4
5
6
7
8
9
10
try:
sponsored_parent = item.find('span', {'class': 'a-declarative'})
sponsored = sponsored_parent.find('span', 'a-color-base').text
except AttributeError:
try:
price_discount_parent = item.find('span', 'a-price a-text-price')
previous_price = price_discount_parent.find('span', 'a-offscreen').text
except AttributeError:
previous_price = ''
...

find() 找不到返回 None,再 .text 就是 AttributeError。所以每个字段都要兜住。

这份代码用了"嵌套 try"来处理"广告商品 vs 普通商品"两种卡片结构,逻辑是:如果是广告位就走广告分支,否则走正常分支。

更好的写法是写一个安全取值函数:

1
2
3
def safe_text(node, selector, attrs=None, default=''):
el = node.find(selector, attrs) if node else None
return el.get_text(strip=True) if el else default

一行一个字段,不用套 5 层 try。

五、折扣计算

1
2
percent_discount = round(((float(price[1:].replace(",", "")) - float(previous_price[1:].replace(",", "")))
/ float(previous_price[1:].replace(",", ""))) * 100, 2)
  • price[1:] 去掉 $;
  • .replace(",", "") 去掉千分位逗号;
  • float() 转数字;
  • 公式:(现价 - 原价) / 原价 × 100。

[1:] 假设货币符号永远是一个字符。"CA$12.99" 就会炸。应该用正则 re.sub(r'[^d.]', '', price)。

六、写 CSV

1
2
3
4
with open(f'{search}.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Description', 'Price Was', 'Price', 'Percent Off', 'Rating', 'Review Count', 'URL'])
writer.writerows(records)

newline='' 必须加(Windows 上不加会多空行),encoding='utf-8' 保中文,writerows 一次写全部行。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# csv:把结果写成表格文件。
import csv
# BeautifulSoup:解析 HTML 树,按标签/属性找元素。
from bs4 import BeautifulSoup
# selenium:驱动真实 Chrome,能执行 JS,适合抓动态渲染的页面。
from selenium import webdriver


# 拼 Amazon 搜索 URL。
def get_url(search_term):
# 模板里 {} 是占位符,后面用 format 填。
template = 'https://www.amazon.ca/s?k={}'
# 空格换成 '+',否则 URL 里会被截断。
search_term = search_term.replace(' ', '+')
url = template.format(search_term)
# 再拼上 '&page={}',留给翻页时填页码。
url += '&page={}'
return url


# 从一个搜索结果卡片里抽出 7 个字段。
def extract_record(item):
# item.h2.a:卡片里的标题链接(h2 > a)。
a_tag = item.h2.a
# .text 取纯文本,strip() 去掉首尾空白与换行。
description = a_tag.text.strip()
# get('href') 取属性;Amazon 给的是相对路径,要拼上域名。
url = 'https://www.amazon.ca' + a_tag.get('href')

# 先判断这块是不是“广告位”(结构不同)。
try:
# find(标签, 属性字典):按 class 找第一个匹配元素。
sponsored_parent = item.find('span', {'class': 'a-declarative'})
# 广告位里取一段文字当价格占位 —— 这段逻辑其实把“sponsored”标签当成了价格来源,
# 只影响展示,不影响主流程。
sponsored = sponsored_parent.find('span', 'a-color-base').text
# 找不到就说明不是广告,走正常商品分支。
except AttributeError:
try:
# 原价(划线价)。
price_discount_parent = item.find('span', 'a-price a-text-price')
# 有些商品没有划线价,用 try 兜住。
previous_price = price_discount_parent.find('span', 'a-offscreen').text
except AttributeError:
# 没有原价时置空串。
previous_price = ''
try:
# 现价。
price_parent = item.find('span', 'a-price')
price = price_parent.find('span', 'a-offscreen').text
except AttributeError:
# 连现价都没有 → 这块不是有效商品,直接返回 None(调用方要判空)。
return
try:
# 评分:Amazon 用 <i> 标签包星星。
rating = item.i.text
# 评论数:这里用“文字长度 < 9”猜是不是数字,很粗糙("1,502" 会被误判成评论数、
# 而 "4.3 out of 5 stars" 才是评分)。
if len(item.find('span', {'class': 'a-size-base'}).text) < 9:
review_count = item.find('span', {'class': 'a-size-base'}).text
else:
review_count = 0
rating = 'No reviews'
# 没有评分元素时给默认值。
except AttributeError:
rating = 'No reviews'
review_count = '0'

# 计算折扣百分比。
if previous_price == '':
percent_discount = '0%'
else:
# price[1:] 去掉货币符号 '$',replace(',', '') 去掉千分位逗号再转 float。
# 硬编码下标 1 假设第一位一定是货币符号,换币种会出错。
percent_discount = round(((float(price[1:].replace(",", "")) - float(
previous_price[1:].replace(",", ""))) / float(previous_price[1:].replace(",", ""))) * 100, 2)
percent_discount = f"{percent_discount}%"

# 按固定顺序打包成元组,正好对应 CSV 的表头。
result = (description, previous_price, price, percent_discount, rating, review_count, url)
return result


# 主流程:开浏览器 → 翻 7 页 → 写 CSV。
def main(search_term):
# webdriver.Chrome(驱动路径) 是 Selenium 3 的写法;Selenium 4 要 Service 对象。
# 另外 "C:Developmentchromedriver.exe" 里的 D 与 c 是无效转义,
# 在 Python 3.12+ 会告 SyntaxWarning,必须写成 r"C:Developmentchromedriver.exe"。
driver = webdriver.Chrome("C:Developmentchromedriver.exe")
# 收集所有记录。
records = []
url = get_url(search_term)

# 翻 1–7 页。
for page in range(1, 8):
# driver.get:真正加载页面(等 DOM 完成,但不保证异步内容已渲染)。
# 原码没有等待/延时,连续快速请求极易被 Amazon 判定为机器人并返回验证页。
driver.get(url.format(page))
# page_source 是渲染后的完整 HTML,交给 BeautifulSoup 解析。
soup = BeautifulSoup(driver.page_source, 'html.parser')
# 搜索结果卡片都带 data-component-type="s-search-result",用它精确定位。
results = soup.find_all('div', {'data-component-type': 's-search-result'})

# 逐卡片抽取。
for item in results:
record = extract_record(item)
print(record)
# 只有抽到有效记录才收进列表(extract_record 可能返回 None)。
if record:
records.append(record)
# 关掉浏览器。
driver.close()
# 写文件:newline='' 防止 Windows 下多出空行,encoding='utf-8' 防止中文乱码。
# 文件名用了全局变量 search —— main 的参数叫 search_term,这里却引用 search,
# 能跑通只是因为 main 外定义了一个同名全局变量,属于隐式依赖。
with open(f'{search}.csv', 'w', newline='', encoding='utf-8') as f:
# csv.writer 逐行写。
writer = csv.writer(f)
# 先写表头。
writer.writerow(['Description', 'Price Was', 'Price', 'Percent Off', 'Rating', 'Review Count', 'URL'])
# writerows:批量写二维数据。
writer.writerows(records)


# 交互式输入搜索词(本脚本是命令行工具,不是 GUI)。
search = input("Search term: ")
main(search)

代码走读

  1. get_url() 构造带页码占位符的 URL。
  2. extract_record(item):从一张卡片里抽 7 个字段,任何一步缺失就 return(跳过这条)。
  3. main():启动 Chrome → 循环 7 页 → 每页用 BS4 解析 → 对每张卡片调 extract_record → 收集 → 关浏览器 → 写 CSV。
  4. search = input(...) 交互式输入关键词。

这份代码的问题

(1) 广告卡片直接 return,被丢弃

1
2
3
4
5
try:
sponsored_parent = item.find('span', {'class': 'a-declarative'})
sponsored = sponsored_parent.find('span', 'a-color-base').text
except AttributeError:
...正常逻辑...

如果找到了 a-declarative(是广告),try 成功,然后函数走到末尾——没有 return 语句,返回 None。所以广告商品全部被丢弃。逻辑上"过滤广告"是对的,但写法让人以为漏了数据。

(2) extract_record 可能返回 None

except AttributeError: return 之后,调用方 if record: 过滤了 None——这个判断救了它,否则 writerows 会崩。

(3) 评分判断用"长度 < 9"

1
2
if len(item.find('span', {'class': 'a-size-base'}).text) < 9:
review_count = item.find('span', {'class': 'a-size-base'}).text

"评论数文本长度小于 9 就当评论数"——"1,234" 是 5 个字符,"Sponsored" 是 9 个字符。靠长度猜语义,极其脆弱。应该看 aria-label 或父节点的 class(s-underline-text)。

(4) 没有随机延时

7 次请求连发,亚马逊会返回验证码页(page_source 里是"Enter the characters you see below"),此时 BS4 抓不到任何结果,程序静默产出空 CSV。

(5) webdriver.Chrome("C:\...") 是旧 API

新版要 Service(...);而且路径写死 Windows,macOS/Linux 跑不了。用 webdriver.Chrome() 让 Selenium 4 自动找驱动。

(6) 每次都覆盖同名 CSV

f'{search}.csv' 用关键词当文件名,中文/特殊字符可能导致写文件失败。

(7) 反爬与合规

亚马逊的 ToS 明确禁止爬虫。技术上能爬 ≠ 允许爬。学习时建议只用 1 页、加延时、不商用;真实需求走 Product Advertising API。

运行结果

1
2
3
Search term: wireless mouse
('Logitech M170 Wireless Mouse', '', 'CA$19.99', '0%', '4.5', '1,234', 'https://www.amazon.ca/...')
...

当前目录生成 wireless mouse.csv,7 列,几百行数据。

易错点

  1. item.h2.a 为 None:有些卡片没有标题结构 → AttributeError。
  2. .text 里有大量空白:必须 .strip()。
  3. find('span', 'a-price') 第二个参数:这是"class 名"的简写,等价 {'class': 'a-price'}。
  4. driver.close() vs quit():close 只关标签页,quit 关整个浏览器进程。

动手改

  • 写 safe_text() 替换嵌套 try。
  • 价格用正则清洗,支持 CA$。
  • 加 time.sleep(random.uniform(2,5))。
  • 抓不到结果时检测"验证码页"并提示。

源文件逐个讲解

3 个文件:

文件 规模 职责
main.py78 行亚马逊搜索页爬虫(7 页 → CSV)
4k monitor.csv285 行 × 7 列跑出来的真实结果(4k monitor 的搜索结果)
README.md8 行说明页

这一天是「爬虫三部曲」的收尾(Day 45 报纸标题 → 46 Billboard → 92 电商),也是全书最后一个「真爬虫」。

4k monitor.csv——7 列的真实结构

1
2
3
Description,Price Was,Price,Percent Off,Rating,Review Count,URL
"Samsung LU32J590UQNXZ 32"" 4K UHD 60Hz Monitor",,$499.98,0%,4.3 out of 5 stars,"1,502",https://www.amazon.ca/...
"Asus VP28UQG 28"" 4K/UHD 3840x2160 1ms DP HDMI Adaptive Sync/FreeSync Eye Care Monitor",$329.00,$298.00,-9.42%,4.3 out of 5 stars,"3,020",https://www.amazon.ca/...

七列,每一列都对应 extract_record() 的一个返回值:

列 来源 特点
Descriptiona_tag.text.strip()含 "" 转义的引号(CSV 规则)
Price Was原价(划线价)可能为空(没打折)
Pricea-offscreen$499.98
Percent Off自己算的注意第二行是 -9.42%(负数!)
Ratingitem.i.text4.3 out of 5 stars(长文本)
Review Counta-size-base"1,502"(带逗号,CSV 会加引号)
URL拼接的绝对地址很长(含 tracking 参数)

⚠️ 第一行数据「戳穿了两个 bug」:

① Price Was 是空的,但 Percent Off 是 0%

这是代码里「previous_price == '' → '0%'」的逻辑——意味着「没打折」被记成「0% 折扣」。

② Percent Off 出现负数 -9.42%

原价 329、现价 298——「现价 - 原价 = -31」,除以原价 = -9.42%。

「折扣」应该是「降了多少」,不该是负数——公式写反了。

正确的「折扣率」:

1
percent_discount = round((prev - price) / prev * 100, 2)   # 正数 = 便宜了 9.42%

main.py(78 行)

(1)get_url():URL 模板

1
2
3
4
5
6
def get_url(search_term):
template = 'https://www.amazon.ca/s?k={}'
search_term = search_term.replace(' ', '+')
url = template.format(search_term)
url += '&page={}'
return url

两步拼接:

  1. 'https://www.amazon.ca/s?k={}' + 搜索词(空格换 +);
  2. 末尾加 &page={}(留给调用方 format(page))。

所以返回的是「带占位符的 URL」——https://www.amazon.ca/s?k=4k+monitor&page={}。

⚠️ 这是「用 format 做模板」的简写——但 {} 留到外面再填,容易看漏。

(2)extract_record():三层嵌套 try

1
2
3
4
5
6
7
8
9
def extract_record(item):
a_tag = item.h2.a
description = a_tag.text.strip()
url = 'https://www.amazon.ca' + a_tag.get('href')

try:
sponsored_parent = item.find('span', {'class': 'a-declarative'})
sponsored = sponsored_parent.find('span', 'a-color-base').text
except AttributeError:

前三行「无条件」取标题和链接——假设每个商品都有 h2 > a。

⚠️ 如果某条结果没有 h2(比如「广告位」或「推荐位」):item.h2 是 None → None.a 抛 AttributeError → 整个爬虫崩(这三行不在 try 里)。

这是「防御性编程不彻底」的典型:最容易出错的地方反而没保护。

(3)第一层 try 的意义:检测「赞助商品」

1
2
3
4
5
try:
sponsored_parent = item.find('span', {'class': 'a-declarative'})
sponsored = sponsored_parent.find('span', 'a-color-base').text
except AttributeError:
...

逻辑很绕:「如果能找到 a-declarative + a-color-base,就说明这是一条「赞助/广告」商品」——然后「什么也不做,直接跳过」(因为 try 块没有 return)。

⚠️ 但 try 块「没有 return」意味着「赞助商品会继续走 except 之后的代码」吗?

不会:try 成功 → 跳过 except → 直接走到 result = (...) 那行——也就是「赞助商品也会被记录」。

⚠️ 而 except 分支里的代码(取原价、取现价、取评分)在「非赞助商品」上执行——这个结构是「反的」:「正常的商品」走了「异常处理」分支。

正确逻辑应该是:

1
2
if item.find('span', {'class': 'a-declarative'}):
return # 跳过赞助商品

「用 try/except 做「条件判断」」是反模式——可读性极差,而且「异常」和「正常」的逻辑混在一起。

(4)第二层:取原价(划线价)

1
2
3
4
5
try:
price_discount_parent = item.find('span', 'a-price a-text-price')
previous_price = price_discount_parent.find('span', 'a-offscreen').text
except AttributeError:
previous_price = ''

item.find('span', 'a-price a-text-price'):第二个参数是「class 名」——'a-price a-text-price' 表示「同时有这两个类」。

⚠️ 但 BeautifulSoup 的第二个位置参数匹配的是「完整 class 字符串」——它能处理「多类名」但要求「顺序完全一致」。

所以「如果 HTML 里写的是 class="a-text-price a-price"(顺序反了)」就找不到。

这是 BeautifulSoup 的著名坑——稳妥写法是 class_=['a-price', 'a-text-price'](列表 = 「同时包含」)。

(5)第三层:取现价,失败就 return

1
2
3
4
5
try:
price_parent = item.find('span', 'a-price')
price = price_parent.find('span', 'a-offscreen').text
except AttributeError:
return

return(不带值)= 返回 None——调用方 if record: 会过滤掉。

这是「跳过无效条目」的干净做法——比「抛异常」好。

⚠️ 但 item.find('span', 'a-price') 会「匹配到第一个 a-price」——而页面上「原价」的容器也有 a-price 类(a-price a-text-price)。

所以「现价」可能取到「原价」——取决于 DOM 顺序。

(6)第四层:评分 + 评论数(含一个「天才 hack」)

1
2
3
4
5
6
7
8
9
10
try:
rating = item.i.text
if len(item.find('span', {'class': 'a-size-base'}).text) < 9:
review_count = item.find('span', {'class': 'a-size-base'}).text
else:
review_count = 0
rating = 'No reviews'
except AttributeError:
rating = 'No reviews'
review_count = '0'

item.i.text:评分在 <i> 标签里(<i class="a-icon-star-small">4.3 out of 5 stars</i>)。

len(...) < 9 这个判断很妙:

Amazon 的评论数可能是 "1,502"(5 字符)或 "12,345"(6 字符);而「无评论」时那个 span 里装的是 "No reviews"(10 字符)。

所以「长度 < 9 = 是数字,≥ 9 = 是 'No reviews'」——用一个「长度阈值」区分了两种语义。

⚠️ 这是「脆弱的启发式」:如果 Amazon 改了文案(比如 "暂无评价")或评论数变成 "1,234,567"(9 字符),判断就错了。

更稳的写法:用正则 ^d[d,]*$ 判断是不是纯数字。

(7)折扣率:公式反了

1
2
3
4
5
6
if previous_price == '':
percent_discount = '0%'
else:
percent_discount = round(((float(price[1:].replace(",", "")) - float(
previous_price[1:].replace(",", ""))) / float(previous_price[1:].replace(",", ""))) * 100, 2)
percent_discount = f"{percent_discount}%"

price[1:]:去掉 $——因为字符串是 "$499.98"。

replace(",", ""):去掉千分位("$1,299.00" → "1299.00")。

公式:(现价 - 原价) / 原价 × 100。

⚠️ 结果是负的(298 - 329 = -31,-31/329 = -9.42%)。

「折扣」应该是「正数表示便宜了多少」——公式应该反过来:

1
percent_discount = round((prev - price) / prev * 100, 2)

⚠️ 另一个问题:price[1:] 假设「第一个字符一定是 $」——如果价格是 "CDN$ 499.98" 或 "499.98"(无符号),[1:] 会切掉一个数字。

(8)main():7 页循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def main(search_term):
driver = webdriver.Chrome("C:Developmentchromedriver.exe")
records = []
url = get_url(search_term)

for page in range(1, 8):
driver.get(url.format(page))
soup = BeautifulSoup(driver.page_source, 'html.parser')
results = soup.find_all('div', {'data-component-type': 's-search-result'})

for item in results:
record = extract_record(item)
print(record)
if record:
records.append(record)
driver.close()

五个要点:

① webdriver.Chrome("C:Developmentchromedriver.exe")

Selenium 3 的写法(位置参数传 driver 路径)——Selenium 4.6+ 已移除,会抛 TypeError。

而且 "C:Development..." 里的 D 是「无效转义」——Python 会「保留原样」并给个 DeprecationWarning(侥幸能跑)。

正确写法:

1
2
from selenium.webdriver.chrome.service import Service
driver = webdriver.Chrome(service=Service("/path/to/chromedriver"))

或者「完全省略」(Selenium 4.6+ 自带 Selenium Manager,自动下载 driver)。

② range(1, 8) = 7 页

Amazon 搜索最多 7 页(约 400 条结果)——这也是「为什么只爬到 285 行」的原因(很多条目被 return None 过滤)。

③ driver.page_source + BeautifulSoup(..., 'html.parser')

「Selenium 渲染 → BS4 解析」的分工:

  • Selenium 负责「执行 JS、等页面加载」;
  • BS4 负责「从 HTML 里抽字段」。

这是「动态页面爬虫」的标准组合(Day 45/46 用 requests 就够了,因为那些页面是静态的)。

④ soup.find_all('div', {'data-component-type': 's-search-result'})

data-component-type 是 Amazon 的「自定义属性」——用来标记「一条搜索结果」。

用「自定义属性」定位比「用 class」稳(因为 class 名带哈希,会变)。

⑤ driver.close() 在循环外

⚠️ 但如果循环里抛异常,close() 不会执行——Chrome 进程会「残留」(跑几次就一堆僵尸进程)。

应该用 try/finally:

1
2
3
4
try:
...
finally:
driver.quit() # quit 比 close 更彻底

close() vs quit():close() 只关当前标签页,quit() 关整个浏览器。

(9)写 CSV

1
2
3
4
    with open(f'{search}.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Description', 'Price Was', 'Price', 'Percent Off', 'Rating', 'Review Count', 'URL'])
writer.writerows(records)

四个细节全对:

细节 作用
with open(...)自动关文件
newline=''防止 Windows 上「多空行」
encoding='utf-8'中文/emoji 不乱码
csv.writer + writerows自动处理「含逗号/引号的字段」

f'{search}.csv':文件名用搜索词(4k monitor.csv 就是这么来的)。

⚠️ 但「搜索词含 / 或 :」时,open 会失败(路径非法)——应该 re.sub(r'[^w-]', '_', search)。

(10)入口

1
2
search = input("Search term: ")
main(search)

「命令行输入搜索词」——没有 if __name__ == "__main__"(所以 import 这个模块会直接开始爬)。

这份代码的问题

  1. item.h2.a 没有保护(遇到无 h2 的条目直接崩)。
  2. 用 try/except 做「是否赞助」的判断(逻辑反了,可读性差)。
  3. 折扣率公式反了(结果是负数)。
  4. price[1:] 假设「首字符一定是 $」。
  5. webdriver.Chrome("路径") 是 Selenium 3 写法(4.6+ 已移除)。
  6. "C:Developmentchromedriver.exe" 是无效转义(D)。
  7. len(...) < 9 判断「有无评论」是脆弱启发式。
  8. driver.close() 不在 finally 里(异常时残留进程)。
  9. print(record) 每次爬都刷屏。
  10. 文件名没做「非法字符」处理。
  11. 没有 if __name__ == "__main__"。
  12. a-price 可能匹配到「原价」容器(取错值)。

README.md(8 行)

标题 Day 92 - Amazon Price Tracker,知识点:Web Scraping、BeautifulSoup、Selenium、CSV。

四个:爬虫、BeautifulSoup、Selenium、CSV。

这一天是「爬虫的最后一课」,也是全书「最真实的一天」:

真实到「它现在跑不了」——三个原因:

  1. webdriver.Chrome(path) 写法已废弃;
  2. Amazon 现在有「反爬」(无头浏览器会看到验证码);
  3. data-component-type 这个属性可能已改。

⚠️ 更重要的现实问题:爬 Amazon 违反其服务条款(robots.txt 明确禁止 /s? 路径)——这段代码「教学可以,商用违法」。

这一天的真正价值是「技术骨架」:

1
2
拼 URL → Selenium 渲染 → BS4 解析 → 抽字段(多层 try)
→ 循环翻页 → 写 CSV

这套骨架,换成「合规的数据源」照样能用——比如「自己公司的后台」、「公开的政府数据」、「有 API 的电商」。

微信收款码 微信
支付宝收款码 支付宝
评论