知识点整理:
- 1、由于淘宝的反爬是比较好的,它的请求也比较兜转,因此直接用requests去请求爬取可能会比较难,因此就可以考虑使用selenium自动化模拟浏览器爬取内容;
- 2、 此处主要是涉及到一些selenium等待加载,输入文本内容,提交文本内容简单操作,再者就是跳转到目标页,分析目标页源码结构
- 3、关于selenium的API文档或参数这篇文章:selenium文档
代码如下:
MONGODB_URL='localhost'
MONGO_DB = 'taobao'
MONGO_TABLE='taobao'
#SERVICE_ARGS=['--load-images=false','disk-cache=true']#这个参数原本是打算用PantomJS 无界面爬取的,但由新版selenium已经放弃支持PantomJS,所以这个参数不用了,无界面爬取将改为Chrome headless
KEYWORDS='美食'
# -*- coding: utf-8 -*-
# @File : spider.py
# @Software: PyCharm
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
from selenium.webdriver.chrome.options import Options
import re
from pyquery import PyQuery as pq
import pymongo
from config import *
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')#上面三行代码就是为了将Chrome不弹出界面,实现无界面爬取
browser = webdriver.Chrome(chrome_options=chrome_options)
#browser = webdriver.PhantomJS(service_args=SERVICE_ARGS)
wait = WebDriverWait(browser,10)
client = pymongo.MongoClient(MONGODB_URL)
db = client[MONGO_DB]
browser.set_window_size(1400,900)#由于浏览器无界面,设置一下大小保证加载
def search():
print('正在搜索....')
try:
browser.get('https://www.taobao.com/')
#等待加载完成执行下面代码
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))
)
submit = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button"))
)
input.send_keys(KEYWORDS)#selenium对输入框输入内容
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:
search()
def next_page(page_number):
print('正在翻页,第%s页' % (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.presence_of_element_located((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_product()
except TimeoutException:
next_page(page_number)
def get_product():
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))
html = browser.page_source #selenium获取当前页面源码
doc = pq(html) #使用pyquery获取想要的信息
items = doc('#mainsrp-itemlist .items .item').items()
for item in items:
product= {
'image':item.find('.pic .img').attr('src'),
'price':item.find('.price').text().replace('\n','',1),
'deal':item.find('.deal-cnt').text(),
'title':item.find(('.title')).text().replace('\n','',10),
'shop':item.find('.shop').text(),
'location':item.find('.location').text()
}
#print(product)
save_to_mongo(product)
def save_to_mongo(result):
try:
if db[MONGO_TABLE].insert(result):
print("存储MongoDB成功",result)
except Exception:
print("存储MongoDB失败",result)
def main():
try:
total = search()
total = int(re.compile('(\d+)').search(total).group(1))
#print(total)
for i in range(2,total+1):
next_page(i)
except Exception:
print("出错啦")
finally:
browser.close()
if __name__ == '__main__':
main()