您好,登錄后才能下訂單哦!
怎么在Python中使用Selenium實現異步加載數據?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
spider.py
#encoding:utf8 import re 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 from bs4 import BeautifulSoup from config import * import pymongo client=pymongo.MongoClient(MONGODB_URL) db=client[MONGODB_DB] ##這里使用PhantomJS,并配置了一些參數 browser=webdriver.PhantomJS(service_args=SERVICE_ArGS) ##窗口的大小,不設置的話,默認太小,會有問題 browser.set_window_size(1400,900) wait=WebDriverWait(browser, 10) def search(): print('正在搜索') ##容易出現超時的錯誤 try: ##等待這兩個模塊都加載好 browser.get("https://www.taobao.com") 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 > div.search-button > button')) ) ######這塊python2搞得鬼 #input.send_keys('\u7f8e\u98df'.decode("unicode-escape")) input.send_keys(KEYWORD.decode("unicode-escape")) submit.click() total = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total')) ) get_product() return total.text except TimeoutException: return search() def next_page(page_number): print('翻頁'+str(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_product() except TimeoutException: return next_page(page_number) #獲取產品信息 def get_product(): products = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .m-itemlist .items')) ) ##拿到網頁 html = browser.page_source soup = BeautifulSoup(html,'lxml') items = soup.select('#mainsrp-itemlist .m-itemlist .items .item.J_MouserOnverReq')# print('*************************到此*************') for item in items: img = item.select('.J_ItemPic.img')[0].get('src') price = item.select('.price.g_price.g_price-highlight > strong')[0].get_text() deal = item.select('.deal-cnt')[0].get_text() title= item.select('.row.row-2.title > a ')[0].get_text().strip() #:nth-of-type(3) shop = item.select('.row.row-3.g-clearfix > .shop > a > span:nth-of-type(2)')[0].get_text() location = item.select('.location')[0].get_text() product={ 'img':img, 'price':price, 'deal':deal, 'title':title, 'shop':shop, 'location':location } #打印一下 import json j = json.dumps(product) dict2 = j.decode("unicode-escape") print dict2 save_to_mongo(product) def save_to_mongo(product): try: if db[MONGODB_TABLE].insert(product): print('存儲到mongodb成功'+str(product)) except Exception: print("存儲到mongodb失敗"+str(product)) def main(): try: total=search() ##搜尋 re正則表達式 s=re.compile('(\d+)') total=int(s.search(total).group(1)) for i in range(2,total+1): next_page(i) except Exception: print('出錯') finally: browser.close() if __name__ == '__main__': main()
config.py
MONGODB_URL='localhost' MONGODB_DB='taobao' MONGODB_TABLE='meishi' SERVICE_ArGS=['--load-images=false','--disk-cache=true'] ##就是美食這兩個字,直接用漢字會報錯 KEYWORD='\u7f8e\u98df'
看完上述內容,你們掌握怎么在Python中使用Selenium實現異步加載數據的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。