提示:此工具基于selenium爬虫框架,故本机必须安装chrome浏览器
文章目录
前言
这里只贴出了源码,我们公司内部使用时打包成了exe文件,windows电脑可以直接运行,如有需要请下你的邮箱。
后续更新计划:
1.增加其他工具支持,比如JS
2.增加多线程,提高运行效率
3.词频统计,自动生成ST关键词,亚马逊标题,五点描述
4.开发Web版本
提示:以下是本篇文章正文内容,下面案例可供参考
一、项目结构
- Main.py - 主程序
- CheckChromeDriver.py - 检查chromedriver版本号
- config.json - 配置文件
- 要查询的Asin.txt - 放入需要查询的Asin
- chromedriver.exe - 爬虫支持程序
二、项目说明
1.Main.py
代码如下:
import os
import xlrd
import xlwt
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.chrome.service import Service
import json
from xlutils.copy import copy
import CheckChromeDriver as ccd
import time
def getKeywordByAsin(asin, pagecount):
browser.get('https://xp.sellermotor.com/selection/asin-query/query')
keywordList = []
# 切换站点
country = browser.find_element(By.ID, 'search_country_code').get_attribute('data-value')
if country != countryCode:
js = '$("#search_country_code").attr("data-value","jp")'
browser.execute_script(js)
country = browser.find_element(By.ID, 'search_country_code').get_attribute('data-value')
print("Current country:", country)
# 输入Asin
browser.find_element(By.XPATH, '//*[@id="search-keyword"]').send_keys(asin)
# 点击查询
browser.find_element(By.XPATH, '//*[@id="market-insight-search"]').click()
# element = browser.find_element(By.CLASS_NAME, 'pagination')
wait.until(presence_of_element_located((By.CLASS_NAME, 'page-item')))
c = browser.find_elements(By.CLASS_NAME, 'page-item')
page_count = c[len(c) - 2].text
if page_count:
next_click_count = int(page_count)
else:
next_click_count = 1
print(next_click_count)
title = None
for i in range(next_click_count):
if i == pagecount:
break
print('------------------Page %s------------------' % (i))
table = browser.find_element(By.ID, 'asinQueryTable')
header = table.find_element(By.TAG_NAME, 'thead')
body = table.find_element(By.TAG_NAME, 'tbody')
rows = body.find_elements(By.TAG_NAME, 'tr')
titles = header.find_elements(By.TAG_NAME, 'th')
if title is None:
title = []
for ti in titles[0:len(titles) - 1]:
title.append(ti.text)
keywordList.append(title)
print(title)
for row in rows:
cols = row.find_elements(By.TAG_NAME, 'td')
keyWord = []
for td in cols[0:len(cols) - 1]:
keyWord.append(td.text)
keywordList.append(keyWord)
print(keyWord)
nextPage = browser.find_element(By.CLASS_NAME, 'page-next')
if nextPage.is_displayed():
nextPage.click()
print('ASIN %s,反查关键词一共 %s 个' % (asin, len(keywordList)))
# print(keywordList)
return keywordList
def start():
chrome_options = webdriver.ChromeOptions()
if headless:
chrome_options.add_argument('--headless') # 隐藏界面
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('-ignore-certificate-errors')
chrome_options.add_argument('-ignore -ssl-errors')
global browser
service = Service("chromedriver.exe")
browser = webdriver.Chrome(service=service, options=chrome_options)
global mainUrl
mainUrl = 'https://xp.sellermotor.com/selection/category/index'
browser.get(mainUrl)
global wait
wait = WebDriverWait(browser, 15)
def login(user, pwd):
browser.get(mainUrl)
# print(f"browser text = {browser.page_source}")
browser.find_element(By.ID, 'rc-tabs-0-tab-password').click()
browser.find_element(By.ID, 'normal_login_username').send_keys(user)
browser.find_element(By.ID, 'normal_login_password').send_keys(pwd)
browser.find_element(By.XPATH, '//*[@id="normal_login"]/div[5]/div/div/div/button').click()
wait = WebDriverWait(browser, 10)
result = wait.until(presence_of_element_located((By.CLASS_NAME, 'username-hide-on-mobile')))
def getConfig():
if not os.path.exists('config.json'):
return '文件不存在'
try:
with open("config.json", 'r') as f:
config = json.load(f)
except:
config = {}
return config
# 保存结果到excel中
def save2Excel(asin, keywords, fileName):
print('------------------ Save2Excel Start ------------------')
print("fileName:", fileName)
print("asin:", asin)
print("keywordList:", keywords)
if keywords: # 判断关键词结果是否为空
if os.path.exists(fileName): # 判断excel文件是否存在,如果不存在则创建,如果存在则copy
oldBook = xlrd.open_workbook(fileName)
newBook = copy(oldBook)
else:
print("创建文件:", fileName)
newBook = xlwt.Workbook(encoding='utf-8')
worksheet = newBook.add_sheet(asin)
# header = ['关键词', '月搜索量', '月点击量', '月点击量占比', '流量占比', '广告排名', '自然排名']
# print(keywords[0]) # Asin:B0823LC5H1,关键词:resin,月搜索量:311599,月点击量:336526,月点击量占比:0.27%,流量占比:66.84%,广告排名:-,自然排名:1-29
# for i in range(0, len(header)): # 写入表头
# worksheet.write(0, i, label=header[i]) # write(行坐标,列坐标,内容)
for j in range(len(keywords)): # ASIN的多个关键词
keywordRow = keywords[j]
for k in range(len(keywordRow)): # 列遍历
worksheet.write(j, k, label=keywordRow[k]) # write(行坐标,列坐标,内容)
newBook.save(fileName)
print('------------------ Save2Excel End ------------------')
def getAsins():
with open('要查询的Asin.txt', 'r') as f:
asins = f.read().split('\n')
f.close()
return asins
if __name__ == "__main__":
ccd.init()
config = getConfig()
print(config)
user = config.get('AccountInfo').get('account')
pwd = config.get('AccountInfo').get('password')
pageCount = config.get('PageCount')
headless = config.get('headless')
countryCode = config.get('countryCode')
start()
login(user, pwd)
asins = getAsins()
try:
if asins:
fileName = None
for asin in asins:
KeyWordsLis = getKeywordByAsin(asin, pageCount)
if fileName is None:
time_tup = time.localtime(time.time())
format_time = '%Y-%m-%d_%a_%H-%M-%S'
cur_time = time.strftime(format_time, time_tup)
fileName = './result/%s-KeyWords-%s.xls' % (countryCode, cur_time)
save2Excel(asin, KeyWordsLis, fileName)
print("执行完成")
finally:
browser.quit()
2.CheckChromeDriver.py
代码如下:
import winreg
import requests
import re
import os
import zipfile
def get_latest_version(url):
'''查询最新的Chromedriver版本'''
rep = requests.get(url).text
time_list = [] # 用来存放版本时间
time_version_dict = {} # 用来存放版本与时间对应关系
result = re.compile(r'\d.*?/</a>.*?Z').findall(rep) # 匹配文件夹(版本号)和时间
for i in result:
time = i[-24:-1] # 提取时间
version = re.compile(r'.*?/').findall(i)[0] # 提取版本号
time_version_dict[time] = version # 构建时间和版本号的对应关系,形成字典
time_list.append(time) # 形成时间列表
latest_version = time_version_dict[max(time_list)][:-1] # 用最大(新)时间去字典中获取最新的版本号
return latest_version
def download_driver(download_url):
'''下载文件'''
file = requests.get(download_url)
with open("chromedriver.zip", 'wb') as zip_file: # 保存文件到脚本所在目录
zip_file.write(file.content)
print('下载成功')
def get_version():
'''查询系统内的Chromedriver版本'''
outstd2 = os.popen('chromedriver --version').read()
return outstd2.split(' ')[1]
def getChromeVersion():
try:
# 从注册表中获得版本号
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
_v, type = winreg.QueryValueEx(key, 'version')
print('Current Chrome Version: {}'.format(_v)) # 这步打印会在命令行窗口显示
return _v
except WindowsError as e:
print('check Chrome failed:{}'.format(e))
def get_path():
'''查询系统内Chromedriver的存放路径'''
outstd1 = os.popen('where chromedriver').read()
return outstd1.strip('chromedriver.exe\n')
def unzip_driver(path):
'''解压Chromedriver压缩包到指定目录'''
f = zipfile.ZipFile("chromedriver.zip", 'r')
for file in f.namelist():
f.extract(file, path)
def download(v):
download_url = url + v + '/chromedriver_win32.zip' # 拼接下载链接
download_driver(download_url)
path = './'
print('替换路径为:', path)
unzip_driver(path)
print('更新后的Chromedriver版本为:', get_version())
pass
def init():
chromeVersion = getChromeVersion()
print('当前的chromed版本为:', chromeVersion)
version = get_version()
print('当前系统内的Chromedriver版本为:', version)
latest_version = get_latest_version(url)
print('最新的chromedriver版本为:', latest_version)
if os.path.exists('chromedriver.exe'):
if version == chromeVersion:
print('当前Chromedriver与Chrome浏览器一致,无需更改')
else:
print('当前Chromedriver与Chrome浏览器不一致,需要进行更新')
download(chromeVersion)
else:
print('未找到Chromedriver,需要下载')
download(chromeVersion)
url = 'http://npm.taobao.org/mirrors/chromedriver/'
if __name__ == "__main__":
init()
3.config.json
代码如下:
{
"AccountInfo": {
"account": "",
"password": ""
},
"PageCount": 5,
"headless": 1,
"countryCode": "us"
}
- AccountInfo:SellerMotor账号密码
- PageCount:要抓取的页数,SellerMotor默认一页是20条数据
- headless:浏览器窗口是否可见,1为不可见,0为可见
- countryCode:目标ASIN所属市场,“us”,“uk”,“de”,“fr”,“es”,“it”,“jp”,“ca”
- 该处使用的url网络请求的数据。
4.要查询的ASIN.txt
代码如下:
B08F7SBVBB
B07FPR3RNQ
B087X22DJN
B07RLJG3P4
B08BZBVFHR
一行只填写一个ASIN,并且需将多余的空行删除,注意此文件的名称不能修改,否则无法读取
5.chromedriver.exe
默认版本,且代码中会检查本机安装的Chrome浏览器版本和chromedriver版本是否匹配,如果不匹配会自动下载匹配的版本
三、使用步骤
第一步,配置参数:
将"config.json"用文本编辑器打开,填入SellerMotor账号以及其他参数,填写完成后保存
第二步,填入要查询的ASIN
将"要查询的Asin.txt"用文本编辑器打开,填入要查询的ASIN,注意不要填多了,否则会执行很久,建议一次查询不超过10个
第三步,双击执行"main.exe",等待控制台执行,执行完毕后会自动生成"关键词列表-xxxx.xls"的文件,这个就是最终的输出文件,所有爬取的关键词都在此文件中。
四、版本更新记录
-
版本号:V1.0.3 更新时间2022年1月16日
更新内容: 1.增加chromedriver版本匹配功能 2.优化文件写入代码,查询完一个Asin立即写入到excel中
-
版本号:V1.0.2 更新时间2022年1月11日
更新内容: 1.增加目标市场配置 2.增加使用说明
-
版本号:V1.0.1 更新时间2022年12月23日
更新内容: 1.完成基础功能