Python使用Selenium+BeautifulSoup爬取淘寶搜索頁
更新時間:2018年02月24日 11:34:48 作者:emmm又餓了
這篇文章主要為大家詳細介紹了Python使用Selenium+BeautifulSoup爬取淘寶搜索頁,具有一定的參考價值,感興趣的小伙伴們可以參考一下
使用Selenium驅動chrome頁面,獲得淘寶信息并用BeautifulSoup分析得到結果。
使用Selenium時注意頁面的加載判斷,以及加載超時的異常處理。
import json
import re
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
# 瀏覽器需要多次使用,所以單獨拿出來。設置一個最長的等待時間,等待目標加載完成
wait = WebDriverWait(browser, 10)
def search(keyword):
# wait容易出現(xiàn)加載時間長的問題,因此用try來捕捉異常
try:
browser.get('https://www.taobao.com')
# 加載需要一定時間的,設置了等待時間,等待加載
# 輸入按鈕的加載等待
input = wait.until(
# 設置加載目標,它是一個選擇器,參數(shù)是需要選擇方式和等待加載的內容
EC.presence_of_element_located((By.CSS_SELECTOR, "#q")) # 選擇CSS選擇器和選擇內容
)
# 提交按鈕
submit = wait.until(
# EC后面是選擇條件,按鈕的加載條件最好的是element_to_be_clickable,意思為元素可以點擊的
EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button"))
)
input.send_keys(keyword) # send_keys對輸入框輸入內容
submit.click() # 提交搜索內容,進入下一個頁面
# 等待頁碼元素加載完成,并返回最大頁碼數(shù)
total = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.total"))
)
# 等待加載完成后獲取信息
get_products()
return total.text
except TimeoutException:
# 超時后重新請求,因此遞歸調用
return search()
def next_page(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.element_to_be_clickable(
(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_products()
except TimeoutException:
return next_page(page_number)
def get_products():
# 判斷單個頁面是否被加載出來
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .items .item')))
html = browser.page_source # 獲取頁面源代碼,所有的
# 使用BS進行分析
soup = BeautifulSoup(html, 'lxml')
items = soup.select('#mainsrp-itemlist .items .item')
for item in items:
image = item.select('.pic .img')[0]['data-src']
price = item.select('.price strong')[0].text
deal = item.select('.deal-cnt')[0].text[:-3]
title = item.select('.title')[0].text.strip()
shop = item.select('.shop')[0].text.strip()
location = item.select('.location')[0].text
product = {
'image': image,
'price': price,
'deal': deal,
'title': title,
'shop': shop,
'location': location
}
save_text(product) # 下載內容
def save_text(product):
# 保存為txt文件,a追加寫模式,編碼模式utf-8
with open('text.txt', 'a', encoding='utf-8') as f:
# 使用JSON把字典轉換為str格式,加換行符
f.write(json.dumps(product, ensure_ascii=False) + '\n')
f.close()
def main():
# 通過關鍵字在淘寶進行搜索
total = search('美食')
# 用正則提取頁碼數(shù)字
total = int(re.compile('(\d+)').search(total).group(1))
# 翻頁
for i in range(2, total+1): # 循環(huán)包含前,不包含尾
next_page(i)
browser.close()
if __name__ == '__main__':
main()
更多內容請參考專題《python爬取功能匯總》進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于Python實現(xiàn)剪切板實時監(jiān)控方法解析
這篇文章主要介紹了基于Python實現(xiàn)剪切板實時監(jiān)控方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09
關于numpy中np.nonzero()函數(shù)用法的詳解
下面小編就為大家?guī)硪黄P于numpy中np.nonzero()函數(shù)用法的詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
Python FastAPI 多參數(shù)傳遞的示例詳解
這篇文章主要介紹了Python FastAPI 多參數(shù)傳遞,FastAPI通過模板來匹配URL中的參數(shù)列表,大概分為三類方式傳遞參數(shù),每種方式結合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-12-12
Python基于matplotlib畫箱體圖檢驗異常值操作示例【附xls數(shù)據文件下載】
這篇文章主要介紹了Python基于matplotlib畫箱體圖檢驗異常值操作,涉及Python針對xls格式數(shù)據文件的讀取、matplotlib圖形繪制等相關操作技巧,并附帶xls數(shù)據文件供讀者下載參考,需要的朋友可以參考下2019-01-01
Python使用eval函數(shù)執(zhí)行動態(tài)標表達式過程詳解
這篇文章主要介紹了Python使用eval函數(shù)執(zhí)行動態(tài)標表達式過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10

