一、Python+Selenium安裝及環(huán)境配置
-
Python環(huán)境安裝
Window系統(tǒng)下,python的安裝很簡(jiǎn)單。訪問python.org/download,下載最新版本,安裝過程與其他windows軟件類似。記得下載后設(shè)置path環(huán)境變量,然后Windows命令行就可以調(diào)用了:
python環(huán)境圖示.png
-
Selenium安裝
Python3.x安裝后就默認(rèn)就會(huì)有pip(pip.exe默認(rèn)在python的Scripts路徑下),使用pip安裝selenium: pip install selenium
后面可以加等號(hào)指定selenium的版本:如:pip install selenium==2.53.0
Selenium環(huán)境圖示.png
-
安裝瀏覽器驅(qū)動(dòng)
Chrome驅(qū)動(dòng):http://npm.taobao.org/mirrors/chromedriver
Firefox驅(qū)動(dòng): [https://github.com/mozilla/geckodriver/releases]
下載與使用瀏覽器相匹配的驅(qū)動(dòng)版本,我這里是將瀏覽器驅(qū)動(dòng)放置在了對(duì)應(yīng)項(xiàng)目的啟動(dòng)目錄下
image.png
二、案例運(yùn)行
案例簡(jiǎn)介:
使用Selenium爬取淘寶商品圖片
#1.安裝selenium安裝Chrome的驅(qū)動(dòng)
#2.引入selenium中的Chrome
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
import requests
#3.創(chuàng)建瀏覽器
browser =Chrome()
#4.讓瀏覽器打開淘寶
browser.get("http://www.taobao.com")
#5.找到頁面中的文本框,輸入男裝.回車
browser.find_element_by_xpath('//*[@id="q"]').send_keys("男裝",Keys.ENTER)
#6.讓程序等待,用戶手動(dòng)掃碼登錄淘寶
while browser.current_url.startswith("https://login.taobao.com"):
print("等待用戶掃碼進(jìn)行下一步操作")
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("下一頁")