python3實現(xiàn)爬取淘寶美食代碼分享
環(huán)境:
ubuntu16.04
python3.5
python庫: selenium, pyquery,pymongo, re
要求:
設(shè)置×××面瀏覽器訪問,并將商品列表存入mongoDB數(shù)據(jù)庫.
分析過程暫時略過
代碼:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
1.爬取淘寶美食的流程
- 搜索關(guān)鍵字: 用selenium打開瀏覽器,模擬輸入關(guān)鍵字,并搜索對應(yīng)的商品列表.
- 分析頁碼并翻頁,模擬翻頁,查看到所有頁面的商品列表.
- 分析并提取商品,利用Pyquery分析源碼,解析得到商品列表.
- 存儲到MONGODB數(shù)據(jù)庫,將商品列表信息存儲到mongoDB數(shù)據(jù)庫.
"""
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 pyquery import PyQuery as pq
import re
from anli.mongoconfig import *
import pymongo
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
#設(shè)置×××面訪問
opt = webdriver.FirefoxOptions()
opt.set_headless()
browser = webdriver.Firefox(options=opt)
#等待瀏覽器加載頁面成功.
wait = WebDriverWait(browser,10)
def search():
try:
# 后臺打開瀏覽器
browser.get('https://www.taobao.com')
# 用CSS選擇器復(fù)制搜索框
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 .search-button')))
EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_TSearchForm > div.search-button > button')))
# 輸入關(guān)鍵字
input.send_keys('美食')
# 點擊搜索按鈕.
submit.click()
# 輸出總共的頁數(shù).
total=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.total')))
# 調(diào)取商品列表的函數(shù).
get_products()
return total.text
except TimeoutException: #超時錯誤.
return search()
# 翻頁
def next_page(page_number):
try:
#注意在firefox和chrome瀏覽器復(fù)制出來的元素不太一樣.
#要傳入的頁碼: 到第幾頁
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,'input.input:nth-child(2)'))
)
#復(fù)制確定按鈕的元素:
submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'span.btn:nth-child(4)')))
#清除頁碼
input.clear()
#輸入當(dāng)前頁碼
input.send_keys(page_number)
#點擊確定按鈕.
submit.click()
#判斷當(dāng)前頁碼是否是當(dāng)前數(shù)字: 復(fù)制高亮頁碼數(shù).
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'span.num'),str(page_number)))
get_products()
except TimeoutException:
next_page(page_number)
#解析jquery源碼
def get_products():
#商品列表:
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))
# 獲取網(wǎng)頁源碼
html = browser.page_source
doc = pq(html)
items = doc('#mainsrp-itemlist .items .item').items()
for item in items:
#定義商品列表詳細信息的字典
product = {
'title': item.find('.title').text(),
'price': item.find('.price').text(),
'image': item.find('.pic .img').attr('src'),
'shop': item.find('.shop').text(),
'deal': item.find('.deal-cnt').text()[:-3],
'location': item.find('.location').text()
}
print(product)
#將商品列表信息保存到mongoDB數(shù)據(jù)庫.
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():
total = search()
# 用正則表達式只匹配出數(shù)字,并打印數(shù)字.
total = int(re.compile('(\d+)').search(total).group(1))
print(total)
for i in range(2,total + 1):
next_page(i)
if __name__=='__main__':
main()
#關(guān)閉×××面瀏覽器.
browser.quit()
#mongoconfig.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
MONGO_URL = 'localhost'
MONGO_DB = 'taobao'
MONGO_TABLE = 'meishi'
安裝和使用mongodb參考:
//www.dbjr.com.cn/article/54758.htm
實現(xiàn)效果:

注意:
chrome瀏覽器和firefox瀏覽器的網(wǎng)頁元素不太一樣.
相關(guān)文章
Django中使用celery完成異步任務(wù)的示例代碼
本篇文章主要介紹了Django中使用celery完成異步任務(wù)的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
python使用xlrd實現(xiàn)檢索excel中某列含有指定字符串記錄的方法
這篇文章主要介紹了python使用xlrd實現(xiàn)檢索excel中某列含有指定字符串記錄的方法,涉及Python使用xlrd模塊檢索Excel的技巧,非常具有實用價值,需要的朋友可以參考下2015-05-05
python?apscheduler?cron定時任務(wù)觸發(fā)接口自動化巡檢過程
這篇文章主要介紹了python?apscheduler?cron定時任務(wù)觸發(fā)接口自動化巡檢過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Python標(biāo)準(zhǔn)庫之typing的用法(類型標(biāo)注)
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫之typing的用法(類型標(biāo)注),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

