爬虫—Selenium爬取JD商品信息

发布时间:2026-10-03 03:55:18 浏览次数:3

一,抓取分析

  本次目标是爬取京东商品信息,包括商品的图片,名称,价格,评价人数,店铺名称。抓取入口就是京东的搜索页面,这个链接可以通过直接构造参数访问https://search.jd.com/Search?keyword=iPhone,显示的就是第一页的搜索结果。

         

 

  页面下方有一个分页导航,包括前7页的链接,下一页的链接和跳转任意页面的链接。

            

 

  这里的商品显示结果一般都是100页,要获取每一页的内容只需要将页码从1到100遍历即可。所以,我们直接在页面输入框中输入要跳转的页面,点击确定按钮就跳转到对应的页面。

  我们在这里不使用直接点击“下一页”,一旦爬取过程中出现异常退出,就无法切换到后续页面了。并且,在爬取过程中也需要记住当前的页码数。当我们利用Selenium加载某一页的商品后,在用相应的解析库解析即可。

二,获取商品列表

   我们首先需要构造一个抓取的URL:https://search.jd.com/Search?keyword=iPhone,参数keyword就是要搜索的关键字。只要改变这个参数,就能获取不同商品的列表,这里我们可以将它定义为一个变量。

# _*_ coding=utf-8 _*_import pymongofrom selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWaitfrom urllib.parse import quote# 配置Seleniumbrowser = webdriver.Chrome(executable_path=r'D:\Google\Chrome\Application\chromedriver')wait = WebDriverWait(browser, 10)keyword = 'iPhone'# 配置MongoDBMONGO_URL = 'localhost'MONGO_DB = 'JD'MONGO_COLLECTION = 'goods'client = pymongo.MongoClient(MONGO_URL)db = client[MONGO_DB]def get_page(page):    """    获取页面    :param page: 页码    :return:    """    print('正在爬取第', page, '页')    try:        url = 'https://search.jd.com/Search?keyword=' + quote(keyword)        browser.get(url)        if page >= 1:            # 页码搜索框加载成功            search_page = wait.until(                EC.presence_of_element_located(                    (By.XPATH, '//p[@>))            )            # 页码确认按钮加载成功            submit = wait.until(                EC.element_to_be_clickable((By.XPATH, '//p[@>)))            print('button')            search_page.clear()            search_page.send_keys(page)            submit.click()        # 当前页码显示标识加载成功,对比我们传入的page,结果一致就返回True,证明是跳转到了传入的page页面        wait.until(            EC.text_to_be_present_in_element(                (By.XPATH, '//p[@>), str(page))        )        # 商品列表加载成功        wait.until(            EC.presence_of_element_located((By.XPATH, '//p[@>))        )        print('Goods show successfully')        get_goods()    except TimeoutException:        get_page(page)def get_goods():    """    获取商品数据    :return:    """    items = browser.find_elements_by_xpath('//p[@>)    for item in items:        goods = {            'img': item.find_element_by_xpath('//p[@]/a/img').get_attribute('src'),            'price': item.find_element_by_xpath('//p[@]/strong').text,            'commit': item.find_element_by_xpath('//p[@]/strong').text,            'title': item.find_element_by_xpath('//p[@]/a').text,            'shop': item.find_element_by_xpath('//p[@]/span/a').text,        }        print(goods)        save_to_mongo(goods)def save_to_mongo(result):    """    保存到MongoDB    :param result: 抓取到的结果:单个商品信息    :return:    """    try:        if db[MONGO_COLLECTION].insert(result):            print('储存到MongoDB成功!')    except Exception:        print('存储到MongoDB失败!')if __name__ == '__main__':    for i in range(1, 10):        get_page(i)

 

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477