溫馨提示×

溫馨提示×

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

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

Python爬蟲學(xué)習(xí)教程:天貓商品數(shù)據(jù)爬蟲

發(fā)布時(shí)間:2020-08-09 14:00:12 來源:ITPUB博客 閱讀:394 作者:python學(xué)習(xí)教程 欄目:編程語言

天貓商品數(shù)據(jù)爬蟲使用教程

  • 下載chrome瀏覽器

  • 查看chrome瀏覽器的版本號(hào),下載對應(yīng)版本號(hào)的chromedriver驅(qū)動(dòng)

  • pip安裝下列包

  • pip install selenium

  • pip install pyquery

  • 登錄微博,并通過微博綁定淘寶賬號(hào)密碼

  • 在main中填寫chromedriver的絕對路徑

  • 在main中填寫微博賬號(hào)密碼

#改成你的chromedriver的完整路徑地址
    chromedriver_path = "/Users/bird/Desktop/chromedriver.exe" 
    #改成你的微博賬號(hào)
    weibo_username = "改成你的微博賬號(hào)"
    #改成你的微博密碼
    weibo_password = "改成你的微博密碼"

效果演示圖片

Python爬蟲學(xué)習(xí)教程:天貓商品數(shù)據(jù)爬蟲

Python爬蟲學(xué)習(xí)教程:天貓商品數(shù)據(jù)爬蟲

項(xiàng)目源碼

# -*- coding: utf-8 -*-    
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.webdriver import ActionChains    
from pyquery import PyQuery as pq    
from time import sleep    
#定義一個(gè)taobao類    
class taobao_infos:    
#對象初始化    
def __init__(self):    
url = 'https://login.taobao.com/member/login.jhtml'    
self.url = url    
options = webdriver.ChromeOptions()    
options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) # 不加載圖片,加快訪問速度    
options.add_experimental_option('excludeSwitches', ['enable-automation']) # 此步驟很重要,設(shè)置為開發(fā)者模式,防止被各大網(wǎng)站識(shí)別出來使用了Selenium    
self.browser = webdriver.Chrome(executable_path=chromedriver_path, options=options)    
self.wait = WebDriverWait(self.browser, 10) #超時(shí)時(shí)長為10s    
#延時(shí)操作,并可選擇是否彈出窗口提示    
def sleep_and_alert(self,sec,message,is_alert):    
for second in range(sec):    
if(is_alert):    
alert = "alert(\"" + message + ":" + str(sec - second) + "秒\")"    
self.browser.execute_script(alert)    
al = self.browser.switch_to.alert    
sleep(1)    
al.accept()    
else:    
sleep(1)    
#登錄淘寶    
def login(self):    
# 打開網(wǎng)頁    
self.browser.get(self.url)    
# 自適應(yīng)等待,點(diǎn)擊密碼登錄選項(xiàng)    
self.browser.implicitly_wait(30) #智能等待,直到網(wǎng)頁加載完畢,最長等待時(shí)間為30s    
self.browser.find_element_by_xpath('//*[@class="forget-pwd J_Quick2Static"]').click()    
# 自適應(yīng)等待,點(diǎn)擊微博登錄宣傳    
self.browser.implicitly_wait(30)    
self.browser.find_element_by_xpath('//*[@class="weibo-login"]').click()    
# 自適應(yīng)等待,輸入微博賬號(hào)    
self.browser.implicitly_wait(30)    
self.browser.find_element_by_name('username').send_keys(weibo_username)    
# 自適應(yīng)等待,輸入微博密碼    
self.browser.implicitly_wait(30)    
self.browser.find_element_by_name('password').send_keys(weibo_password)    
# 自適應(yīng)等待,點(diǎn)擊確認(rèn)登錄按鈕    
self.browser.implicitly_wait(30)    
self.browser.find_element_by_xpath('//*[@class="btn_tip"]/a/span').click()    
# 直到獲取到淘寶會(huì)員昵稱才能確定是登錄成功    
taobao_name = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.site-nav-bd > ul.site-nav-bd-l > li#J_SiteNavLogin > div.site-nav-menu-hd > div.site-nav-user > a.site-nav-login-info-nick ')))    
# 輸出淘寶昵稱    
print(taobao_name.text)    
# 獲取天貓商品總共的頁數(shù)    
def search_toal_page(self):    
# 等待本頁面全部天貓商品數(shù)據(jù)加載完畢    
good_total = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#J_ItemList > div.product > div.product-iWrap')))    
#獲取天貓商品總共頁數(shù)    
number_total = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.ui-page > div.ui-page-wrap > b.ui-page-skip > form')))    
page_total = number_total.text.replace("共","").replace("頁,到第頁 確定","").replace(",","")    
return page_total    
# 翻頁操作    
def next_page(self, page_number):    
# 等待該頁面input輸入框加載完畢    
input = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.ui-page > div.ui-page-wrap > b.ui-page-skip > form > input.ui-page-skipTo')))    
# 等待該頁面的確定按鈕加載完畢    
submit = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.ui-page > div.ui-page-wrap > b.ui-page-skip > form > button.ui-btn-s')))    
# 清除里面的數(shù)字    
input.clear()    
# 重新輸入數(shù)字    
input.send_keys(page_number)    
# 強(qiáng)制延遲1秒,防止被識(shí)別成機(jī)器人    
sleep(1)    
# 點(diǎn)擊確定按鈕    
submit.click()    
# 模擬向下滑動(dòng)瀏覽    
def swipe_down(self,second):    
for i in range(int(second/0.1)):    
js = "var q=document.documentElement.scrollTop=" + str(300+200*i)    
self.browser.execute_script(js)    
sleep(0.1)    
js = "var q=document.documentElement.scrollTop=100000"    
self.browser.execute_script(js)    
sleep(0.2)    
# 爬取天貓商品數(shù)據(jù)    
def crawl_good_data(self):    
# 對天貓商品數(shù)據(jù)進(jìn)行爬蟲    
self.browser.get("https://list.tmall.com/search_product.htm?q=羽毛球")    
err1 = self.browser.find_element_by_xpath("//*[@id='content']/div/div[2]").text    
err1 = err1[:5]    
if(err1 == "喵~沒找到"):    
print("找不到您要的")    
return    
try:    
self.browser.find_element_by_xpath("//*[@id='J_ComboRec']/div[1]")    
err2 = self.browser.find_element_by_xpath("//*[@id='J_ComboRec']/div[1]").text    
#print(err2)    
err2 = err2[:5]    
if(err2 == "我們還為您"):    
print("您要查詢的商品書目太少了")    
return    
except:    
print("可以爬取這些信息")    
# 獲取天貓商品總共的頁數(shù)    
page_total = self.search_toal_page()    
print("總共頁數(shù)" + page_total)    
# 遍歷所有頁數(shù)    
for page in range(2,int(page_total)):    
# 等待該頁面全部商品數(shù)據(jù)加載完畢    
good_total = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#J_ItemList > div.product > div.product-iWrap')))    
# 等待該頁面input輸入框加載完畢    
input = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.ui-page > div.ui-page-wrap > b.ui-page-skip > form > input.ui-page-skipTo')))    
# 獲取當(dāng)前頁    
now_page = input.get_attribute('value')    
print("當(dāng)前頁數(shù)" + now_page + ",總共頁數(shù)" + page_total)    
# 獲取本頁面源代碼    
html = self.browser.page_source    
# pq模塊解析網(wǎng)頁源代碼    
doc = pq(html)    
# 存儲(chǔ)天貓商品數(shù)據(jù)    
good_items = doc('#J_ItemList .product').items()    
# 遍歷該頁的所有商品    
for item in good_items:    
good_title = item.find('.productTitle').text().replace('\n',"").replace('\r',"")    
good_status = item.find('.productStatus').text().replace(" ","").replace("筆","").replace('\n',"").replace('\r',"")    
good_price = item.find('.productPrice').text().replace("¥", "").replace(" ", "").replace('\n', "").replace('\r', "")    
good_url = item.find('.productImg').attr('href')    
print(good_title + "   " + good_status + "   " + good_price + "   " + good_url + '\n')    
# 精髓之處,大部分人被檢測為機(jī)器人就是因?yàn)檫M(jìn)一步模擬人工操作    
# 模擬人工向下瀏覽商品,即進(jìn)行模擬下滑操作,防止被識(shí)別出是機(jī)器人    
self.swipe_down(2)    
# 翻頁,下一頁    
self.next_page(page)    
# 等待滑動(dòng)驗(yàn)證碼出現(xiàn),超時(shí)時(shí)間為5秒,每0.5秒檢查一次    
# 大部分情況不會(huì)出現(xiàn)滑動(dòng)驗(yàn)證碼,所以如果有需要可以注釋掉下面的代碼    
# sleep(5)    
WebDriverWait(self.browser, 5, 0.5).until(EC.presence_of_element_located((By.ID, "nc_1_n1z"))) #等待滑動(dòng)拖動(dòng)控件出現(xiàn)    
try:    
swipe_button = self.browser.find_element_by_id('nc_1_n1z') #獲取滑動(dòng)拖動(dòng)控件    
#模擬拽托    
action = ActionChains(self.browser) # 實(shí)例化一個(gè)action對象    
action.click_and_hold(swipe_button).perform() # perform()用來執(zhí)行ActionChains中存儲(chǔ)的行為    
action.reset_actions()    
action.move_by_offset(580, 0).perform() # 移動(dòng)滑塊    
except Exception as e:    
print ('get button failed: ', e)    
if __name__ == "__main__":    
# 使用之前請先查看當(dāng)前目錄下的使用說明文件README.MD    
# 使用之前請先查看當(dāng)前目錄下的使用說明文件README.MD    
# 使用之前請先查看當(dāng)前目錄下的使用說明文件README.MD    
chromedriver_path = "/Users/bird/Desktop/chromedriver.exe" #改成你的chromedriver的完整路徑地址    
weibo_username = "改成你的微博賬號(hào)" #改成你的微博賬號(hào)    
weibo_password = "改成你的微博密碼" #改成你的微博密碼    
a = taobao_infos()    
a.login() #登錄    
a.crawl_good_data() #爬取天貓商品數(shù)據(jù)

平臺(tái)網(wǎng)站經(jīng)常變動(dòng),可以做參考

很多初學(xué)者,對Python的概念都是模糊不清的,Python能做什么,學(xué)的時(shí)候,該按照什么線路去學(xué)習(xí),學(xué)完往哪方面發(fā)展,想深入了解,詳情可以點(diǎn)擊有道云筆記鏈接了解:http://note.youdao.com/noteshare?id=7df52a4961924a8d98d3bc774cbfe54d

向AI問一下細(xì)節(jié)

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

AI