zoukankan      html  css  js  c++  java
  • Python爬虫学习==>第十二章:使用 Selenium 模拟浏览器抓取淘宝商品美食信息

    学习目的:


     

       selenium目前版本已经到了3代目,你想加薪,就跟面试官扯这个,你赢了,工资就到位了,加上一个脚本的应用,结局你懂的

    正式步骤


     

    需求背景:抓取淘宝美食

    Step1:流程分析

    • 搜索关键字:利用selenium驱动浏览器搜索关键字,得到查询后的商品列表
    • 分析页码并翻页:得到商品页码数,模拟翻页,得到后续页面的商品列表
    • 分析提取商品内容:利用PyQuery分析源码,解析得到商品列表
    • 存储至MongoDB:将商品列表信息存储到数据库MongoDB

    Step2:代码分析

    chromedriver 下载:http://chromedriver.storage.googleapis.com/index.html

    # -*-  coding:utf-8 -*-
    import re
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    import time
    from pyquery import PyQuery as pq
    from config_taobao import *
    import pymongo
    
    ###数据库设置###
    client = pymongo.MongoClient(MONGO_URL)
    #client后的数据库用[]
    db = client[MONGO_DB]
    
    #公共参数
    driver = webdriver.Chrome()
    url = 'https://www.taobao.com'
    wait = WebDriverWait(driver, 10)
    
    def search():
        driver.get(url)
        #显式等待参考了官方api文档 http://selenium-python.readthedocs.io/waits.html
        searchbox = wait.until(EC.presence_of_element_located((By.ID, "q")))
        submit = driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button')
        #下面是测试代码,验证提交按钮是否可用
        submit1 = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="J_TSearchForm"]/div[1]/button')))
    #    print(submit1.text)
        #搜索关键字可以设置为用户收入,在公共参数表用Python的input函数
        searchbox.send_keys('美食')
        submit.click()
        #等待页面加载出搜索结果的总页数
        total = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@class="total"]')))
        #页码加载完成后,获取商品信息
        get_products()
        return total.text
    
    def next_page(page_number):
    
        try:
            input = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')))
            submit = driver.find_element_by_css_selector('#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')#wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')))
            input.clear()
            input.send_keys(page_number)
            #此处设置等待时间是因为我本地的网速过快,不休眠一下,无法正常点击
            time.sleep(3)
            submit.click()
            time.sleep(3)
            #验证输入页页码和高亮页是否匹配
            wait.until(
                EC.text_to_be_present_in_element(
                    (By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)
                )
            )
            get_products()
        #下面的异常抓取是函数递归,点击确定按钮失败后,重新加载此函数
        except TimeoutException:
            next_page(page_number)
    
    def get_products():
        #pyquery的用法,我也不是很了解,后续加强学习,现在知道这么用
        wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item'))
        )
        html = driver.page_source
        doc = pq(html)
        items = doc('#mainsrp-itemlist .items .item').items()
        for item in items:
            product = {
                'image':item.find('.pic .img').attr('src'),
                'price':item.find('.price').text().strip()[3:],
                'name':item.find('.title').text(),
                'shopname':item.find('.shop').text()
    
            }
            print(product)
            save_product_info(product)
    
    ##保存信息至MongoDB
    def save_product_info(result):
        if db[MONGO_Table].insert(result):
            print('存储成功')
    
    def main():
        total = search()
        total = int(re.compile('(d+)').search(total).group(1))
        print(total)
        for i in range(2,total+1):
            next_page(i)
    
    if __name__ == '__main__':
        main()

    配置文件信息:

    # -*-  coding:utf-8 -*-
    
    MONGO_URL = 'localhost'
    MONGO_DB = 'taobao'
    MONGO_Table = 'product'

    学习总结:


     

       爬虫越来越好玩了,继续学

  • 相关阅读:
    ie用document.getElementsByName获取不到
    js_设置光标到文本的最后位置
    js-转大小写
    mysql查询数据表的路径
    myeclipse导出javadoc时特殊字符 尖括号
    keyCode码集合
    mysql查询数据库约束
    oracle查询每个表的占用空间
    MYSQL复制表
    MacOs上的Intellij idea高频快捷键总结(2018.1版本)
  • 原文地址:https://www.cnblogs.com/wuzhiming/p/8787594.html
Copyright © 2011-2022 走看看