溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python3怎么實現(xiàn)爬取淘寶美食

發(fā)布時間:2021-05-07 12:28:06 來源:億速云 閱讀:229 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹python3怎么實現(xiàn)爬取淘寶美食,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

python的五大特點是什么

python的五大特點:1.簡單易學,開發(fā)程序時,專注的是解決問題,而不是搞明白語言本身。2.面向?qū)ο?,與其他主要的語言如C++和Java相比, Python以一種非常強大又簡單的方式實現(xiàn)面向?qū)ο缶幊獭?.可移植性,Python程序無需修改就可以在各種平臺上運行。4.解釋性,Python語言寫的程序不需要編譯成二進制代碼,可以直接從源代碼運行程序。5.開源,Python是 FLOSS(自由/開放源碼軟件)之一。

環(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選擇器復制搜索框
    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瀏覽器復制出來的元素不太一樣.
    #要傳入的頁碼: 到第幾頁
    input = wait.until(
      EC.presence_of_element_located((By.CSS_SELECTOR,'input.input:nth-child(2)'))
    )
    #復制確定按鈕的元素:
    submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'span.btn:nth-child(4)')))

    #清除頁碼
    input.clear()
    #輸入當前頁碼
    input.send_keys(page_number)

    #點擊確定按鈕.
    submit.click()

    #判斷當前頁碼是否是當前數(shù)字: 復制高亮頁碼數(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'

實現(xiàn)效果:

python3怎么實現(xiàn)爬取淘寶美食

注意:

chrome瀏覽器和firefox瀏覽器的網(wǎng)頁元素不太一樣.

以上是“python3怎么實現(xiàn)爬取淘寶美食”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI