618要来了,不买点啥总觉得少了点什么,正好我用了5 6 年的电脑想换,这可不就来活了嘛!我们用Python也能简单获取某东上的mac电脑价格。
不整虚的,直接就是一个冲,来看代码:
import requests
from bs4 import BeautifulSoup
def get_jd_laptops():
url = "https://search.jd.com/Search"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36",
}
params = {
"keyword": "Mac 笔记本电脑",
"enc": "utf-8",
"qrst": "1",
"rt": "1",
"stop": "1",
"vt": "2",
"wq": "mac 笔记本电脑",
"page": "1",
"s": "1",
"click": "0",
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
return response.text
else:
return None
def extract_prices(html):
soup = BeautifulSoup(html, "html.parser")
items = soup.find_all("li", class_="gl-item")
prices = []
for item in items:
price_tag = item.find("strong", class_="J_price")
if price_tag:
price = price_tag.get_text().strip()
prices.append(price)
return prices
# 测试代码
html = get_jd_laptops()
if html:
prices = extract_prices(html)
for price in prices:
print(price)
else:
print("请求失败")
这里多说一句,我们可以根据需要进一步处理提取到的价格数据,比如转换为数值类型进行计算或其他操作。如果有uu打算在亚马逊之类的海外平台购买,也可以整活:
import requests
from bs4 import BeautifulSoup
def get_amazon_laptops():
url = "https://www.amazon.com/s"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36",
}
params = {
"k": "Mac笔记本电脑",
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
return response.text
else:
return None
def extract_prices(html):
soup = BeautifulSoup(html, "html.parser")
items = soup.find_all("div", class_="s-result-item")
prices = []
for item in items:
price_tag = item.find("span", class_="a-offscreen")
if price_tag:
price = price_tag.get_text().strip()
prices.append(price)
return prices
# 测试代码
html = get_amazon_laptops()
if html:
prices = extract_prices(html)
for price in prices:
print(price)
else:
print("请求失败")
不过以我的经验来看,618并不是在海外购物平台买东西的绝佳时机,这种除了官网日常做活动,还得看黑五这种。
这里要提醒大家的是,如果你想要爬亚马逊这种平台,建议是要使用全球HTTP代理的,国内HTTP代理不好使。也别上什么免费的全球HTTP代理了,他们网页反爬只会更严格。类似bright data这种老牌的厂商是OK,不过属实有点贵,还是看兜够不够硬。
全球HTTP代理我不是很建议用国外品牌的,毕竟人家老家就是国外,而且人的工作机制在那,万一有点什么问题,能给你当天回复算你运气好。
国内的无非就是那几家,挑几家看看价格,然后选你心理价位最合适的就OK。
给大家伙看看价格:
ipidea:
青果网络:
smartproxy:
……
自己看吧!