Selenium |【案例篇】selenium爬取淘寶圖片

一、Python+Selenium安裝及環境配置
  • Python環境安裝

Window系統下,python的安裝很簡單。訪問python.org/download,下載最新版本,安裝過程與其他windows軟件類似。記得下載后設置path環境變量,然后Windows命令行就可以調用了:

python環境圖示.png
  • Selenium安裝

Python3.x安裝后就默認就會有pip(pip.exe默認在python的Scripts路徑下),使用pip安裝selenium: pip install selenium
后面可以加等號指定selenium的版本:如:pip install selenium==2.53.0

Selenium環境圖示.png
  • 安裝瀏覽器驅動

Chrome驅動:http://npm.taobao.org/mirrors/chromedriver
Firefox驅動: [https://github.com/mozilla/geckodriver/releases]
下載與使用瀏覽器相匹配的驅動版本,我這里是將瀏覽器驅動放置在了對應項目的啟動目錄下

image.png
二、案例運行

案例簡介:
使用Selenium爬取淘寶商品圖片

#1.安裝selenium安裝Chrome的驅動
#2.引入selenium中的Chrome
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
import requests


#3.創建瀏覽器
browser =Chrome()

#4.讓瀏覽器打開淘寶
browser.get("http://www.taobao.com")

#5.找到頁面中的文本框,輸入男裝.回車
browser.find_element_by_xpath('//*[@id="q"]').send_keys("男裝",Keys.ENTER)

#6.讓程序等待,用戶手動掃碼登錄淘寶
while browser.current_url.startswith("https://login.taobao.com"):
    print("等待用戶掃碼進行下一步操作")
    time.sleep(1)

n=1
while 1:

#7.找到頁面中的所有item

    items = browser.find_element_by_class_name("m-itemlist").find_element_by_class_name("item")

    for item in items:
        src_path = item.find_element_by_class_name("pic-box").find_element_by_class_name("img").get_attribute("data-src")
        src_path = "http:"+src_path

        #下載這張圖片,保存在文件中
        open("f{n}.jpg", mode="wb").write(requests.get(src_path).content)
        n+=1

    browser.find_element_by_class_name("m-page").find_element_by_class_name("next").click()
    time.sleep(2)
    print("下一頁")


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容