前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python抓取亚马逊指定商品的所有页面

Python抓取亚马逊指定商品的所有页面

原创
作者头像
jackcode
发布2023-06-01 16:07:21
5020
发布2023-06-01 16:07:21
举报
文章被收录于专栏:爬虫资料爬虫资料
随着全球疫情逐步缓解,外贸出口市场正在逐步恢复。作为全球最大的电商平台之一,亚马逊的数据反映了外贸出口的趋势和变化。

中国商家在亚马逊上的商品交易总额(GMV)逐年攀升。2017年,中国卖家在亚马逊上的GMV达到了480亿美元,占据了亚马逊总GMV的18%。而到了2022年,中国卖家的GMV已经增长至2010亿美元,占比为26%。

中国商家在不同的亚马逊站点上的占比存在差异。在TOP 10000卖家中,中国卖家平均占比达到了42%。其中,在亚马逊西班牙站,中国卖家占比最高,达到了54%;其次是法国站,中国卖家占比为48%;意大利站的中国卖家占比为45%;在英国站,中国卖家占比为34%;在德国站,中国卖家占比为29%。

为了提高亚马逊电商卖家的竞争力和利润,他们应该如何选择和优化商品呢?其中,最重要的工作就是定期分析亚马逊上同类商品的相关信息,用于分析市场前景和商品信息等关键因素。下面提供数据分析demo,用于对亚马逊指定商品的全部页面进行采集:

代码语言:python
复制
import undetected_chromedriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as ExpectedConditions
import pandas as pd
import time
from fake_useragent import UserAgent

from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


def get_url(search_term):
    # 根据搜索词生成亚马逊的搜索链接
    template = 'https://www.amazon.com/s?k={}'
    search_term = search_term.replace(' ', '+')
    url = template.format(search_term)
    return url


def scrape_records(item):
    # 从商品元素中提取商品信息
    atag = item.h2.a
    description = atag.text.strip()
    url = 'https://amazon.com' + atag.get('href')

    price_parent = item.find('span', 'a-price')
    price = price_parent.find('span', 'a-offscreen').text.strip() if price_parent and price_parent.find('span', 'a-offscreen') else ''

    rating_element = item.find('span', {'class': 'a-icon-alt'})
    rating = rating_element.text.strip() if rating_element else ''

    review_count_element = item.find('span', {'class': 'a-size-base s-underline-text'})
    review_count = review_count_element.text.strip() if review_count_element else ''

    result = (description, price, rating, review_count, url)
    return result


def scrape_amazon(search_term):
    ua = UserAgent()
    
    # 创建Options对象
    options = Options()
    
    
    # 设置 亿牛云 爬虫代理加强版 用户名、密码、IP和端口号
    options.add_argument('--proxy-server=http://16YUN:16IP@www.16yun.cn:31000')
    
    # 设置随机User-Agent
    options.add_argument(f"user-agent={ua.random}")
    
    driver = undetected_chromedriver.Chrome(options=options)
    url = get_url(search_term)
    driver.get(url)
    time.sleep(5)
    records = []

    while True:
        # 滚动到页面底部加载更多商品
        time.sleep(5)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        soup = BeautifulSoup(driver.page_source, 'html.parser')
        results = soup.find_all('div', {'data-component-type': 's-search-result'})

        for item in results:
            try:
                record = scrape_records(item)
                records.append(record)
            except Exception as e:
                print(f"Error scraping item: {e}")

        # 检查页面是否有"Next"按钮
        try:
            nextButton = driver.find_element(By.XPATH, '//a[text()="Next"]')
            driver.execute_script("arguments[0].scrollIntoView();", nextButton)
            WebDriverWait(driver, 10).until(ExpectedConditions.element_to_be_clickable(nextButton))
            nextButton.click()
        except NoSuchElementException:
            print("Breaking as Last page Reached")
            break

    driver.close()

    # 处理商品信息并转换为DataFrame对象
    df = pd.DataFrame(records, columns=['Description', 'Price', 'Rating', 'Review Count', 'URL'])
    return df


# 获取用户输入的搜索词
search_term = 'washing machine'

# 爬取亚马逊的搜索结果
df = scrape_amazon(search_term)

# 将DataFrame导出为Excel文件
df.to_excel('output.xlsx', index=False)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档