使用Selenium驅(qū)動(dòng)chrome頁(yè)面,獲得淘寶信息并用BeautifulSoup分析得到結(jié)果。
使用Selenium時(shí)注意頁(yè)面的加載判斷,以及加載超時(shí)的異常處理。
import jsonimport refrom bs4 import BeautifulSoupfrom selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECbrowser = 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()
新聞熱點(diǎn)
疑難解答
圖片精選