selenium爬取淘宝商品

2018-07-30  本文已影响0人  xin激流勇进
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
import re
from bs4 import BeautifulSoup
import json


browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)


def search():
    try:
        browser.get('https://www.taobao.com/')
        input = wait.until(EC.presence_of_element_located((By.ID, 'q')))
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button')))
        input.send_keys('美食')
        submit.click()
        total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total')))
        get_products()
        return total.text
    except:
        search()


def next_page(page_number):
    try:
        input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.form > input')))
        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)
        submit.click()
        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:
        next_page(page_number)


def get_products():
    wait.until((EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist'))))
    soup = BeautifulSoup(browser.page_source, 'lxml')
    for item in soup.find('div', {'id': 'mainsrp-itemlist'}).find_all('div', {'class': 'item'}):
        title = item.select_one('.title').text.strip()
        price = item.select_one('.price').find('strong').text
        location = item.select_one('.location').text
        product = {'title': title, 'price': price, 'location': location}
        print(product)
        # print(len(soup.find('div', {'id': 'mainsrp-itemlist'}).find_all('div', {'class': 'item'})))
        save_to_file(product)
        # json.dump(product, file)
        # print(file)

def save_to_file(data):
    file = open('data.txt', 'a')
    json.dump(data, file)
    file.close()


def main():
    file = open('data.txt', 'w')
    total = search()
    # total = int(re.compile('(\d+)').search(total).group(1))
    for i in range(2, 4):
        next_page(i)
    browser.close()
    file.close()


if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读