selenium抓取淘宝商品

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

#我们需要用到MongoDB数据库,用于存储爬取下来的数据
#需要用pyquery来解析代码
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

#这里我们先构造一个webdriver对象,使用PhantomJS无界面浏览器,指定抓取的商品,这里我们选择抓取iphoneX,设定最长等待时间为10秒
browser = webdriver.PhantomJS(service_args=SERVICE_ARGS)
wait = WebDriverWait(browser, 10)
KEYWORD = ‘iphoneX‘

#定义一个方法,首先访问商品链接。
def index_page(page):
    try:
        url = ‘https://s.taobao.com/search?q=‘ + quote(KEYWORD)
        browser.get(url)
        #这里我们加入判断,如果页面不大于1,也就是在第一页的时候,等待页面加载完成,如果页面大于1,也就是想要翻页的时候,我们定位到‘页面搜索框’和‘确定’按钮,
        #定位到上述两个按钮以后,我们执行清空、传参和点击的操作,就可以到达我们想要翻页的目的,然后继续执行。
        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)))
        #这里我们等待页面加载完成后,加入.m-itemlist .items .item这个选择器,用于选择我们想要的商品信息部分。
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ‘.m-itemlist .items .item‘)))
        get_products()
    except TimeoutException:
        index_page(page)

#定义一个解析商品信息的方法,这里使用到pyquery来解析,具体用法不再介绍,使用css选择器就可以。
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)

#这里,我们想要将爬下来的数据保存到MongoDB数据库中,首先创建一个MongoDB的链接对象,我们定义了操作数据库的名称,collection的名称。
MONGO_DB = ‘taobao‘
MONGO_COLLECTION = ‘products‘
client = pymongo.MongoClient(host = ‘localhost‘)
db = client[MONGO_DB]

#用insert方法将数据插入。
def save_to_mongo(result):
    try:
        if db[MONGO_COLLECTION].insert(result):
            print(‘success‘)
    except Exception:
        print(‘fail‘)

#这里我们设置最大页码数为20,调用for循环。
MAX_PAGE = 20
def main():
    for i in range(1, MAX_PAGE + 1):
        index_page(i)

#执行
if __name__ == ‘__main__‘:
    main()

原文地址:https://www.cnblogs.com/houziaipangqi/p/9665426.html

时间: 2024-08-29 19:33:52

selenium抓取淘宝商品的相关文章

利用Selenium爬取淘宝商品信息

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

selenium抓取淘宝数据报错:warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless

ssh://[email protected]:22/root/anaconda3/bin/python3 -u /www/python3/maoyantop100/meishi_selenium.py /root/anaconda3/lib/python3.6/site-packages/selenium/webdriver/phantomjs/webdriver.py:49: UserWarning: Selenium support for PhantomJS has been depre

使用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 im

用PHP抓取淘宝商品的用户晒单评论+图片实例

为什么想起来做这个功能?是因为前段时间在做一个淘客网站的时候,想到是否能抓取到淘宝商品的买家秀呢?经过一番折腾发现,淘宝商品用户评价信息是通过Ajax来调取的,通过嗅探网址发现,评论数据的请求接口是: https://rate.tmall.com/list_detail_rate.htm?itemId=524394294771&spuId=341564036&sellerId=100414600&order=3&currentPage=1&append=0&

使用Selenium模拟浏览器抓取淘宝商品美食信息

淘宝页面比较复杂,含有各种请求参数和加密参数,如果直接请求或者分析Ajax将会非常繁琐.Selenium是一个自动化测试工具,可以驱动浏览器去完成各种工作,比如模拟点击.输入和下拉等多种功能,这样我们只需关心操作,不需要关心后台发生了怎么样的请求下面对具体操作步骤进行详述. 创建webdriver对象 #创建一个WebDriver对象 from Selenium import webdriver browser = webdriver.Chrome() 大多数网络应用程序都使用AJAX技术.当浏

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——

爬虫实战--使用Selenium模拟浏览器抓取淘宝商品美食信息

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as E

利用 selenium 抓取 淘宝信息

import lxml from bs4 import BeautifulSoup import time from selenium import webdriver import re driver = webdriver.PhantomJS() driver.set_window_size(1600,20000) driver.get("https://item.taobao.com/item.htm?spm=2013.1.0.0.bLyAul&id=17676925595&quo

使用selenium模拟浏览器抓取淘宝信息

通过Selenium模拟浏览器抓取淘宝商品美食信息,并存储到MongoDB数据库中. 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.webdri