使用Selenium爬取淘宝商品

import pymongo
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from pyquery import PyQuery as pq
from urllib.parse import quote

# browser = webdriver.Chrome()
# browser = webdriver.PhantomJS(service_args=SERVICE_ARGS)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(‘--headless‘)
browser = webdriver.Chrome(chrome_options=chrome_options)

MONGO_URL = ‘localhost‘
MONGO_DB = ‘taobao‘
MONGO_COLLECTION = ‘products‘

KEYWORD = ‘ipad‘

MAX_PAGE = 100

SERVICE_ARGS = [‘--load-images=false‘, ‘--disk-cache=true‘]

wait = WebDriverWait(browser, 10)
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

def index_page(page):
    """
    抓取索引页
    :param page: 页码
    """
    print(‘正在爬取第‘, page, ‘页‘)
    try:
        url = ‘https://s.taobao.com/search?q=‘ + quote(KEYWORD)
        browser.get(url)
        if page > 1:
            input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ‘#mainsrp-pager div.form > input‘)))
            submit = wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, ‘#mainsrp-pager div.form > span.btn.J_Submit‘)))
            input.clear()
            input.send_keys(page)
            submit.click()
        wait.until(
            EC.text_to_be_present_in_element((By.CSS_SELECTOR, ‘#mainsrp-pager li.item.active > span‘), str(page)))
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ‘.m-itemlist .items .item‘)))
        get_products()
    except TimeoutException:
        index_page(page)

def get_products():
    """
    提取商品数据
    """
    html = browser.page_source
    doc = pq(html)
    items = doc(‘#mainsrp-itemlist .items .item‘).items()
    for item in items:
        product = {
            ‘image‘: item.find(‘.pic .img‘).attr(‘data-src‘),
            ‘price‘: item.find(‘.price‘).text(),
            ‘deal‘: item.find(‘.deal-cnt‘).text(),
            ‘title‘: item.find(‘.title‘).text(),
            ‘shop‘: item.find(‘.shop‘).text(),
            ‘location‘: item.find(‘.location‘).text()
        }
        print(product)
        save_to_mongo(product)

def save_to_mongo(result):
    """
    保存至MongoDB
    :param result: 结果
    """
    try:
        if db[MONGO_COLLECTION].insert(result):
            print(‘存储到MongoDB成功‘)
    except Exception:
        print(‘存储到MongoDB失败‘)

def main():
    """
    遍历每一页
    """
    for i in range(1, MAX_PAGE + 1):
        index_page(i)
    browser.close()

if __name__ == ‘__main__‘:
    main()

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
from pyquery import PyQuery
from pymongo import MongoClient

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)
KEYWORD = ‘iPad‘

def index_page(page):
    """
    抓取索引页
    :param page: 页码
    """
    print(‘正在爬取第‘, page, ‘页‘)
    try:
        url = ‘https://s.taobao.com/search?q=‘ + quote(KEYWORD)
        browser.get(url)
        if page > 1:
            input = wait.until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, ‘#mainsrp-page div.form > input‘)
                )
            )
            # 利用 CSS 选择器,选择 id=mainsrp-page 的节点的所有元素,再从中选择父节点为 div 的 input 元素
            # 其中 div 的属性 class=form。此时选择的是输入框
            submit = wait.until(
                EC.element_to_be_clickable(
                    (By.CSS_SELECTOR, ‘#mainsrp-pager div.form > span.btn.J_Submit‘)
                )
            )
            # 利用CSS选择器,选择 id=mainsrp-pager 的节点的所有元素,再从中选择父节点为 div 的 span 元素
            # 其中 div 的属性 class=form,span 的属性 class=btn J_Submit。此时选择的是"确定"按钮
            input.clear()                   # 清除输入框中的内容
            input.send_keys(page)           # 在输入框中输入页码 page
            submit.click()                  # 点击确定按钮
        wait.until(
            EC.text_to_be_present_in_element(
                (By.CSS_SELECTOR, ‘#mainsrp-pager li.item.active > span‘), str(page)
            )
        )
        # 利用CSS选择器,选择 id=mainsrp-pager 的节点的所有元素,在从中选出 span 节点,
        # 其中span节点的父节点为li节点,li节点的属性class=item active
        wait.until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, ‘.m-itemlist .items .item‘)
            )
        )
        # 利用 CSS 选择器,选择 class=m-iremlist 的节点,从该节点中选择 class-items 的节点,再从中选择 class=item 的节点的所有元素
        # 这里对应的是这一页中的每个淘宝商品
        get_products()
    except TimeoutException:
        index_page(page)

def get_products():
    """
    提取商品数据
    """
    html = browser.page_source                          # 获取源代码
    doc = PyQuery(html)                                 # 解析html
    items = doc(‘#mainsrp-itemlist .items .item‘).items()
    for item in items:
        # 这个 item 中
        product = {
            ‘image‘: item.find(‘.pic .J_ItemPic.img‘).attr(‘data-src‘),
            # 找到 class=pic 的节点,再从中选择 class=J_ItemPic img 的节点,最后通过 attr() 方法获取 data-src 属性
            ‘price‘: item.find(‘.price.g_price.g_price-highlight‘).text(),
            # 找到属性 class=price g_price g_price-highlight 的节点,获取其文本(价格)
            ‘deal‘: item.find(‘.deal-cnt‘).text(),
            # 找到 class=deal-cnt 的节点,获取其文本(付款人数)
            ‘title‘: item.find(‘row.row-2.title‘).text(),
            # 找到属性值 class=row row-2 title 的节点,获取其文本(商品价格)
            ‘shop‘: item.find(‘.shop‘).text(),
            # 获取 class=shop 的节点的文本(店铺)
            ‘location‘: item.find(‘.location‘).text()
            # 获取 class=location 的节点的文本(店铺地址)
        }
        print(product)
        save_to_mongo(product)

MONGO_URL = ‘localhost‘
MONGO_DB = ‘TaoBao‘
MONGO_COLLECTION = ‘products‘
client = MongoClient(MONGO_URL)
db = client[MONGO_DB]

def save_to_mongo(result):
    """
    将爬取结果保存到MongoDB
    :param result: 结果
    :return:
    """
    try:
        if db[MONGO_COLLECTION].insert(result):
            print(‘存储到 MongoDB 成功‘)
    except Exception:
        print(‘存储到 MongoDB 失败‘)

MAX_PAGE = 100

def main():
    """
    遍历每一页
    :return:
    """
    for i in range(1, MAX_PAGE + 1):
        index_page(i)
    browser.close()

if __name__ == ‘__main__‘:
    main()

与上面的一样

原文地址:https://www.cnblogs.com/liyihua/p/11230984.html

时间: 2024-07-29 10:37:30

使用Selenium爬取淘宝商品的相关文章

利用Selenium爬取淘宝商品信息

一.  Selenium和PhantomJS介绍 Selenium是一个用于Web应用程序测试的工具,Selenium直接运行在浏览器中,就像真正的用户在操作一样.由于这个性质,Selenium也是一个强大的网络数据采集工具,其可以让浏览器自动加载页面,这样,使用了异步加载技术的网页,也可获取其需要的数据. Selenium模块是Python的第三方库,可以通过pip进行安装: pip3 install selenium Selenium自己不带浏览器,需要配合第三方浏览器来使用.通过help命

Selenium爬取淘宝商品概要入mongodb

准备: 1.安装Selenium:终端输入 pip install selenium 2.安装下载Chromedriver:解压后放在…\Google\Chrome\Application\:如果是Mac,可放入/usr/locl/bin,并将此目录放入环境变量 3.安装pyquery:终端输入 pip install pyquery 4.安装pymongo:终端输入 pip install pymongo 5.安装MongoDB的PyCharm插件:Preferences——Plugins——

python基础项目实战:selenium控制浏览器爬取淘宝商品信息

今天为大家介绍一个Python利用selenium打开浏览器的方式来爬取淘宝商品的信息,下面就来看看,关于selenium的知识点,是如何做到控制浏览器获取网站的信息 导入第三方库 关键词搜索 抓取索引页 大家在学python的时候肯定会遇到很多难题,以及对于新技术的追求,这里推荐一下我们的Python学习扣qun:784758214,这里是python学习者聚集地!!同时,自己是一名高级python开发工程师,从基础的python脚本到web开发.爬虫.django.数据挖掘等,零基础到项目实

爬虫实例之selenium爬取淘宝美食

这次的实例是使用selenium爬取淘宝美食关键字下的商品信息,然后存储到MongoDB. 首先我们需要声明一个browser用来操作,我的是chrome.这里的wait是在后面的判断元素是否出现时使用,第二个参数为等待最长时间,超过该值则抛出异常. browser = webdriver.Chrome() wait = WebDriverWait(browser,10) 声明好之后就需要进行打开网页.进行搜索的操作. #使用webdriver打开chrome,打开淘宝页面,搜索美食关键字,返回

用selenium爬取淘宝美食

'''利用selenium爬取淘宝美食网页内容''' import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.su

利用Python爬虫爬取淘宝商品做数据挖掘分析实战篇,超详细教程

项目内容 本案例选择>> 商品类目:沙发: 数量:共100页  4400个商品: 筛选条件:天猫.销量从高到低.价格500元以上. 项目目的 1. 对商品标题进行文本分析 词云可视化 2. 不同关键词word对应的sales的统计分析 3. 商品的价格分布情况分析 4. 商品的销量分布情况分析 5. 不同价格区间的商品的平均销量分布 6. 商品价格对销量的影响分析 7. 商品价格对销售额的影响分析 8. 不同省份或城市的商品数量分布 9.不同省份的商品平均销量分布 注:本项目仅以以上几项分析为

selenium抓取淘宝商品

我们知道,javascript动态渲染页面不止ajax这一种,有些网站可能整个都是由javascript渲染后生成的,还有些网站,比如淘宝,它虽然有ajax请求,但其中加入了很多复杂的参数,需要耗费大量时间才能找出规律,这时候,我们就可以用selenium,它可以直接模仿浏览器运行,并且抓取在运行时的源码,不用管ajax那些复杂的数,此次我们使用一种无界面的浏览器PhantomJS,它可以做到不用打开浏览器就可以运行,另外,需要正确安装好Selenium库. #我们需要用到MongoDB数据库,

Python3爬虫爬取淘宝商品数据

这次的主要的目的是从淘宝的搜索页面获取商品的信息.其实分析页面找到信息很容易,页面信息的存放都是以静态的方式直接嵌套的页面上的,很容易找到.主要困难是将信息从HTML源码中剥离出来,数据和网页源码结合的很紧密,剥离数据有一定的难度. 然后将获取的信息写入excel表格保存起来,这次只爬取了前面10页 的内容.在运行代码的过程中发现,30页后面的数据有问题,出现了手机价格为0的情况,这是不符合实际的,码也没有写错误处理的代码. 这次先写个粗略的,有点凌乱的感觉,下次有时间再系统的整理整理吧. im

selenium+pyquery爬取淘宝商品信息

import re from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_condi