Selenium爬取淘宝关键词搜索ipad页面中的 title,shop,location,image,price,deal信息,并保存到csv文件中:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:Awen
@file:spidertaobao.py
@time:2020/04/20
"""
from selenium import webdriver
from selenium.common.exceptions import TimeoutException #超时防错机制
from selenium.webdriver.common.by import By #定位元素用的   可用CSS中的select器
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait #等待 网页转圈圈
from urllib.parse import quote # 将汉字转码为浏览器识别的内容
from pyquery import PyQuery #用于解析页面
import time
import pandas as pd

KEYWORD = 'iPad'
browser = webdriver.Chrome(r'D:\Scrapy\chromedriver.exe')
wait = WebDriverWait(browser,5)

#爬取第n页面(所有页面)
def crawl_page(page):
    try:
        url = 'https://s.taobao.com/search?q='+quote(KEYWORD)
        browser.get(url)
        print('正在爬取页面……')
        time.sleep(5) #睡眠几秒,用于手机扫码

        #实现翻页功能
        if page>1:
            #判断可显示
            page_box=wait.until(ec.presence_of_all_elements_located((By.CSS_SELECTOR,'.input.J_Input')))
            #判断可点击
            click_button = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR,'.btn.J_Submit')))
            page_box.clear()
            page_box.send_keys(page)
            click_button.click()

        #等待一定的时间(时间为之前设置wait的时间10s),直到通过CSS选择器能在页面找到某个元素
        #如果超时还没有找到就继续向后执行
        wait.until(
            ec.presence_of_all_elements_located(
            (By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')
            )
        )
        get_products()
    except:
        crawl_page(page)


#爬取商品
def get_products():
    res = []
    print('正在解析商品……')
    html = browser.page_source #获取网页源代码
    doc = PyQuery(html) #解析网页源代码
    items = doc('#mainsrp-itemlist .items .item').items() #定位所有商品
    for item in items:
        # print(item)
        # print('正在获取商品详请……')
        product = {
            'title':item.find('.title').text(), # #mainsrp-itemlist .items .item .title a span
            'shop': item.find('.shop').text(),
            'location': item.find('.location').text(),
            'image': item.find('.img').attr('src'),
            'price': item.find('.price').text(),
            'deal': item.find('.deal-cnt').text()
                   }
        res.append(product)
    # 如果程序未跑通,可在这里直接将获取的结果res写入到taobao.csv文件中
    return res

def save_date(res):
    df = pd.DataFrame(res)
    # df['title'] = df['title'].str.replace('\n', '').str.replace('【', '').str.replace('】', '').str.replace('[','').str.replace(']', '').str.replace('/', '')
    df.to_csv('taobao.csv')

if __name__ == '__main__':
    res = crawl_page(1)  # 爬取当前第一页
    # print(res)
    save_date(res)

对标题title进行分词,制作中文词云:

import pandas as pd
import jieba
import re
import numpy as np
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
from PIL import Image
from matplotlib import pyplot as plt
import os
from os import path

d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()

stopword = [line.rstrip() for line in open("stopwords.txt", 'r', encoding='utf-8')]

newdata = []
def read_data():
    csv_data = pd.read_csv('taobao.csv',usecols=[1,6])
    # print(csv_data)
    for i in range(len(csv_data)):
        title = csv_data['title'][i]
        newdata.append(title)
    # print(newdata)
    return newdata

def cut_word(data):
    newtext = []
    linesword = ''.join(data)
    text = re.sub(r'\d+', ' ', linesword)  # 去除数字
    text = jieba.lcut(text)  # 分词
    for word in text:
        if word not in stopword:  # 去停用词 + 词性筛选
            newtext.append(word)
    lineswords = ' '.join(newtext)
    # print(lineswords)
    return lineswords

def wordcloud(text):
    text = text.strip()
    # 设置中文字体
    # font_path = 'E:\Fonts思源黑体字体全套\SourceHanSansCN-Regular.otf'  # 思源黑体
    font_path = 'D:\Fonts\simkai.ttf'
    # 读取背景图片
    background_Image = np.array(Image.open(path.join(d, "2.jpg")))
    # 提取背景图片颜色
    img_colors = ImageColorGenerator(background_Image)
    # 设置中文停止词
    stopwords = set('')
    # stopwords.update(['但是','一个','自己','因此','没有','很多','可以','这个','虽然','因为','这样','已经','现在','一些','比如','不是','当然','可能','如果','就是','同时','比如','这些','必须','由于','而且','并且','他们'])
    wc = WordCloud(
        font_path=font_path,  # 中文需设置路径 字体设置
        margin=2,  # 页面边缘
        mask=background_Image,
        scale=2,
        max_words=200,  # 最多词个数
        min_font_size=4,  #
        stopwords=stopwords,
        random_state=42,
        background_color='white',  # 背景颜色
        # background_color = '#C3481A', # 背景颜色
        max_font_size=100,
    )
    wc.generate(text)
    # 获取文本词排序,可调整 stopwords
    process_word = WordCloud.process_text(wc, text)
    sort = sorted(process_word.items(), key=lambda e: e[1], reverse=True)
    # print(sort[:50]) # 获取文本词频最高的前50个词
    # 设置为背景色,若不想要背景图片颜色,就注释掉
    wc.recolor(color_func=img_colors)
    # 存储图像
    wc.to_file('词云.jpg')
    # 显示图像
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    data = read_data()
    text = cut_word(data)
    wordcloud(text)

原图片:

                                                                            

词云展示:

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐