一、使用selenium 模拟浏览器操作爬取淘宝商品信息
之前我们已经成功尝试分析Ajax来抓取相关数据,但是并不是所有页面都可以通过分析Ajax来完成抓取。
比如,淘宝,它的整个页面数据确实也是通过Ajax获取的,但是这些Ajax接口参数比较复杂,可能会包含加密密钥等,
所以如果想自己构造Ajax参数,还是比较困难的。
对于这种页面,最方便快捷的抓取方法就是通过Selenium
目标:利用Selenium抓取淘宝商品并用pyquery解析得到商品的图片、名称、价格、购买人数、店铺名称和店铺所在地信息
完整代码
#-*-coding:utf-8-*- #抓取淘宝商品信息 from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote from pyquery import PyQuery as pq
import pymongo
import time browser = webdriver.Chrome()
wait = WebDriverWait(browser,15)
KEYWORD = 'iPad' #抓取索引页 def index_page(page):
print('正在爬取第',page,'页') try:
url = 'https://s.taobao.com/search?q='+ quote(KEYWORD)
browser.get(url) if page > 1:
input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager div.form > input')))
submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager div.form > span.btn.J_Submit')))
input.clear()
input.send_keys(page)
submit.click()
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager li.item.active > span'),str(page)))
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.m-itemlist .items .item')))
get_products()
except TimeoutException:
index_page(page) #解析商品列表 def get_products():
html = browser.page_source
doc = pq(html)
items = doc('#mainsrp-itemlist .items .item').items() for item in items:
product = {
'image' : item.find('.pic .img').attr('data-src'),
'price' : item.find('.price').text(),
'deal' : item.find('.dral-cnt').text(),
'title' : item.find('.title').text(),
'shop' : item.find('.shop').text(),
'location' : item.find('.localtion').text()
}
print(product)
save_to_mongo(product) #保存到MongoDB MONGO_URL = 'localhost'
MONGO_DB = 'taobao'
MONGO_COLLECTION = 'products'
client = pymongo.MongoClient(host=MONGO_URL,port=27017)
db = client[MONGO_DB]
def save_to_mongo(result):
try:
if db[MONGO_COLLECTION.insert(result)]:
print('存储成功')
except Exception:
print('存储失败') #main函数 MAX_PAGE = 5 def main():
url = 'https://s.taobao.com/search?q=' + quote(KEYWORD)
browser.get(url)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#J_QRCodeImg')))
time.sleep(10)
for i in range(1,MAX_PAGE+1):
index_page(i) main()