selenium 爬蟲爬取京東商城商品資訊

2021-10-08 14:11:11 字數 2495 閱讀 6406

看完用selenium爬取**商品資訊的網課,於是乎想著自己也整乙個selenium程式來爬取京東以作鞏固。寫了幾個小時的**,通過不斷除錯,學到了很多細節上的處理,完整**在下方,使用時修改搜尋的引數就可以開始爬取了,事先要安裝goole chrome的驅動。最終爬取的結果儲存在了products陣列中,需要新增其他處理時,直接在程式最後使用陣列來呼叫爬取的結果。執行結果不展示了,就是把資訊輸出出來,因為要等待網頁載入,所以執行時間有點久。

from selenium import webdriver

import time

defsearch_product

(key)

:#向搜尋框輸入內容

driver.find_element_by_id(

'key'

).send_keys(key)

defclick_search()

:#搜尋按鈕

driver.find_element_by_class_name(

'button'

).click(

)def

pagenum()

:#獲取總的頁數

pagenum=driver.find_element_by_class_name(

'p-skip'

).text

return pagenum[1:

-10]def

page_next()

: page=driver.find_element_by_class_name(

'pn-next'

)

page.click(

)if __name__==

'__main__'

:

products=

count=

0

url=

""

driver=webdriver.chrome(

)

driver.get(url)

search_product(

'特崙蘇'

)

driver.maximize_window(

)

click_search(

)

time.sleep(3)

#程序掛起3秒,等待視窗載入完成,未載入完成會導致爬取的資料不全,或者元素無法定位

driver.execute_script(

"window.scrollby(0, 8000)"

)#下拉滾動條以使網頁中的全部商品資訊載入,不下拉進度條,下半部分資訊不顯示

time.sleep(1)

while

(count<

int(pagenum())

):

products_info=driver.find_elements_by_xpath(

'//div[@class = "gl-i-wrap"]'

)for div in products_info:

name=div.find_element_by_xpath(

'.//div[@class="p-name p-name-type-2"]'

)#商品名稱

price=div.find_element_by_xpath(

'.//div[@class="p-price"]//i'

)#**

shop=div.find_element_by_xpath(

'.//div[@class="p-shop"]'

)#店鋪名稱

commit=div.find_element_by_xpath(

'.//div[@class="p-commit"]//a'

)#評價

(name.text,price.text+

'元',shop.text,commit.text+

))

pagenum=count+

1print

('第'

+str

(pagenum)

+'頁已提取,共'

+pagenum()+

'頁')

page_next(

)

time.sleep(

3)

driver.execute_script(

"window.scrollby(0, 8000)"

)

time.sleep(

1)

count+=

1

driver.quit(

)print

(products)

selenium爬取京東商品

from selenium import webdriver import time import pandas as pd url browser webdriver.chrome browser.get url 找到頁面中的搜尋框,然後輸入想找的商品 browser.find element b...

selenium爬取京東商品名與價格

簡單實現自動化模擬人爬取京東,當然這爬不了 有自動化爬取監測 import time from selenium import webdriver from lxml import html etree html.etree 建立物件 browner webdriver.chrome browner...

利用Python爬蟲爬取京東(小規模)

一.開發環境 本文執行環境為windows10 python3.7 使用的第三方庫有selenium 操作瀏覽器 pymysql 資料庫 bs4 解析 chrome chromedriver 二.先決條件 利用京東的搜尋結果,然後把結果儲存起來 那麼接下來就是找到京東搜尋的相關url。因為可見即可爬...