亚马逊还是一个不错,挺有意思的网站,相对于国内电商平台,淘宝而言,它对于你爬的容忍度似乎更高?不知道反爬频率是多大,而不同的国家与地区有不同的网站,最关键的就是域名后缀,比如国内是cn,国际美国亚马逊是com,而法国亚马逊恰好是一个国内可以访问的站点。
一个网友可以问询的东西,法国亚马逊采集,花了一点时间,搞了个很基础的demo,好像还是常规的一些东西,除了商品大图花费了不少时间,发现可以在js里可以获取到完整的商品大图,急着去买菜,所以也就有了这样一个基础版本。
通过调试,还是发现会存在获取不到的问题,不知道是反爬限制还是其他原因,待研究。
商品标题的获取
其实直接取title应该更简单,我这里是取得页面内容的标题。
req.xpath('//h1[@id="title"]/span[@id="productTitle"]/text()')
商品属性的获取
这里没有花很多时间去看,没看出是否存在链接,仅仅是把所有属性给提取出来了。
req.xpath('//ul[@class="a-unordered-list a-nostyle a-button-list a-declarative a-button-toggle-group a-horizontal a-spacing-top-micro swatches swatchesSquare"]/li')
商品描述的获取
进行了简单的格式化处理
productDescriptions=req.xpath('//div[@id="productDescription"]//text()')
productDescription=''.join(productDescriptions)
商品大图的获取
花费了不少时间,主要是找到图片链接费了不少力气,写入到js中了,没办法,只能用正则获取到图片链接。
imgs_text=re.findall(r'ImageBlockATF(.+?)return data;',html,re.S)[0]
imgs=re.findall(r'"large":"(.+?)","main":',imgs_text,re.S)
exe打包
链接:
https://pan.baidu.com/s/1rMqVT3s00EORUziJekq2SA
提取码:
35ds
附源码,仅供参考,学习,交流:
#法国亚马逊商品采集
#20200524 by 微信:huguo00289
#https://www.amazon.fr/dp/B07CNJTCBB/ref=twister_B07RVPW2GT?_encoding=UTF8&th=1
# -*- coding=utf-8 -*-
import requests
from fake_useragent import UserAgent
import re,os,time,random
from lxml import etree
def ua():
ua=UserAgent()
headers={"User-Agent":ua.random}
return headers
def get_data(url):
id=re.findall(r'dp/(.+?)/',url,re.S)[0]
print(f'>>>您输入的商品链接id为:{id},正在采集,请稍后..')
response=requests.get(url,headers=ua(),timeout=8)
time.sleep(2)
if response.status_code == 200:
print(">>>恭喜,获取网页数据成功!")
html=response.content.decode('utf-8')
with open(f'{id}.html','w',encoding='utf-8') as f:
f.write(html)
req=etree.HTML(html)
h1=req.xpath('//h1[@id="title"]/span[@id="productTitle"]/text()')
print(h1)
h1=h1[0].strip()
print(f'商品标题:{h1}')
productDescriptions=req.xpath('//div[@id="productDescription"]//text()')
productDescription=''.join(productDescriptions)
print(f'商品描述:{productDescription}')
imgs_text=re.findall(r'ImageBlockATF(.+?)return data;',html,re.S)[0]
imgs=re.findall(r'"large":"(.+?)","main":',imgs_text,re.S)
print(imgs)
text=f'商品标题:{h1}\n商品描述:{productDescription}\n商品图片{imgs}'
with open(f'{id}.txt','w',encoding='utf-8') as f:
f.write(text)
print(f">>>恭喜,保存商品数据成功,已保存为{id}.txt")
lis=req.xpath('//ul[@class="a-unordered-list a-nostyle a-button-list a-declarative a-button-toggle-group a-horizontal a-spacing-top-micro swatches swatchesSquare"]/li')
if len(lis)>1:
print(f">>>商品存在分类属性,共有{len(lis)}分类!")
spans=req.xpath('//div[@class="twisterTextDiv text"]/span[@class="a-size-base"]/text()')
print(spans)
if __name__ == '__main__':
print("亚马逊采集工具-by 微信公众号:二爷记")
print("BUG反馈 微信:huguo00289")
print("请输入要采集的网址,按回车运行")
url=input("请输入要采集的商品网址:")
try:
get_data(url)
except Exception as e:
if "port=443" in e:
print("获取网页链接超时,正在重试..")
get_data(url)
print("采集完毕!")
print("8s后,程序自动关闭,BUG反馈 微信:huguo00289")
time.sleep(8)
本文分享自 Python与SEO学习 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!