python+webdriver 模擬用戶交互工具


概述:

 

步驟:

安裝webdriver:

Windows:

  pc:chrome(有頭瀏覽器,除用命令控制瀏覽器外其余與瀏覽器相同,個人用chrome)

    phantomjs(無頭瀏覽器,后台操作,不彈出瀏覽器)

    安裝方法:下載好對應的zip文件,提取其中的chromedriver.exe/phantomjs.exe放於自行創建的文件夾中即可(實例放置於D盤新建Driver文件夾中)

Linux:

  (案例為使用樹莓派安裝phantomjs,並無chrome安裝方法,個人一般使用爬蟲在樹莓派或者vps工作會在pc調試好再進行上傳,也就沒必要安裝chrome。。。好吧,我承認我懶只找到安裝phantomjs的方法)詳見:"Installing PhantomJS on the Raspberry Pi"

首先,退至主目錄,通過git獲得phantomjs-raspberry.git

cd ~

若未安裝git或不確定可使用

sudo pip install git

獲取phantomjs-raspberry.git(需要等待幾分鍾進行下載,應該因為家里網垃圾等了小二十分鍾吧我。。/攤手)

git clone https://github.com/piksel/phantomjs-raspberrypi.git

給下載好的文件中bin目錄下phantomjs文件加入權限

chmod -x ~/phantomjs-raspberrypi/bin/phantomjs
chmod 775 ~/phantomjs-raspberrypi/bin/phantomjs

通過ln -s進行軟連接

sudo ln -s /home/pi/phantomjs-raspberrypi/bin/phantomjs /usr/bin/

至此,phantomjs應該已經安裝成功,可輸入

phantomjs -v 

查詢phantomjs的版本號,若存在版本號即為安裝成功

安裝selenium庫:

  於命令行輸入:

pip install selenium

代碼使用:

# 導入selenium庫
from selenium import webdriver


# 確認模擬瀏覽器位置
chromePath = r'D:\Driver\chromedriver.exe'  # chrome模擬瀏覽器

phantomjsPath = r'D:\Driver\phantomjs.exe'  # phantomjs瀏覽器


# 指明瀏覽器路徑和瀏覽器類型
wd = webdriver.Chrome(executable_path= chromePath)  # Chrome瀏覽器
wd = webdriver.PhantomJS(executable_path = phantomjsPath)  # Phantomjs瀏覽器


# 打開網頁
wd.get(url)


# 獲取網頁對應標簽的文本信息
wd.find_element_by_xpath('文本Xpath位置').text


# 網頁填寫框進行填寫
wd.find_element_by_xpath('填寫框Xpath位置').send_keys('填寫內容')


# 若有標簽'display'="none"導致標簽未顯示,可更改display值為'block'
# 引自'http://www.cnblogs.com/fnng/p/5365900.html'
# 示例為WKJ出生日期選項,"li"為標簽名,[18]為第18位"li"標簽
js = 'document.querySelectorAll("li")[18].style.display="block";'  
wd.execute_script(js)


# 網頁按鈕點擊
wd.find_element_by_xpath('按鈕Xpath位置').click()  # 若為按鈕
wd.find_element_by_xpath('按鈕Xpath位置').submit()  # 若為表單

  

大致使用方法就是這些,新人第一次發微博,大家見諒。。。。。。。。

ps: 保存cookie文件實行免登陸操作參見:python+webdriver 網頁自動登錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM