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

