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()

猜你喜欢

转载自www.cnblogs.com/houziaipangqi/p/9665426.html