引入,可以参考selenium的api
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 re import time from pyquery import PyQuery as pq import pymongo连接mongodb数据库
hostName = 'localhost' databaseName = 'taobao' tableName = 'taobao' port = 27017 client = pymongo.MongoClient(hostName, port) db = client[databaseName] tb = db[tableName]配置全局的浏览器
# 拿到css选择器 copy -》 copy selector browser = webdriver.Chrome() wait = WebDriverWait(browser, 10)定义首次搜索方法
def search(): # 处理第一个页面 try: # 需要处理Timeout异常 browser.get("https://www.taobao.com/") # 拿到输入框 input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#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_product() return total.text except TimeoutException: return search() # 递归的去进行查询定义后续的搜索方法
def next_page(page_number): # 处理第二个往后的页面 try: # 需要处理Timeout异常 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() # text_to_be_present_in_element # 指定节点是否包含当前元素 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_product() except TimeoutException: next_page(page_number)
页面展示出来之后,拿到网页源代码,并使用PyQuery进行抓取
def get_product(): wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-itemlist .items .item"))) html = browser.page_source # 拿到网页源代码 doc = pq(html) # 传入html,得到dom节点 items = doc('#mainsrp-itemlist .items .item').items() # 调用items方法,得到所有选择的内容 for item in items: product = { 'image': item.find('.pic .img').attr('src'), 'price': item.find('.price').text(), 'deal': item.find('.deal-cnt').text()[:-3], 'title': item.find('.title').text(), 'shop': item.find('.shop').text(), 'location': item.find('.location').text() } print(product) tb.insert(product)