1. 程式人生 > 實用技巧 >web自動化中的js操作:用js獲取url、hostname、port、title等值並列印輸出

web自動化中的js操作:用js獲取url、hostname、port、title等值並列印輸出

"""
實現功能:使用python+selenium+js完成,任意開啟一個連結,用js獲取url、hostname、port、title等值並列印
作者:檸檬草不孤單
"""
from selenium import webdriver
driver=webdriver.Chrome()
#最大化視窗
driver.maximize_window()
#隱式等待
driver.implicitly_wait(5)
#開啟淘寶
driver.get("https://www.taobao.com/?spm=a2107.1.0.0.259d11d9vireQv")
#js獲取url
js_url="return window.location.href
" url=driver.execute_script(js_url) #列印url print("url:"+url) driver.get(url) #列印title print("title:"+driver.title) #js獲取hostname js_hostname="return window.location.hostname" hostname=driver.execute_script(js_hostname) print("hostname:"+hostname) #js獲取port js_port="return window.location.port" port
=driver.execute_script(js_port) print("port:"+port) #js獲取protocol js_protocol="return window.location.protocol" protocol=driver.execute_script(js_protocol) print("protocol:"+protocol) #搜尋框輸入 driver.find_element_by_xpath("//input[@id='q']").send_keys("襯衫")

演示結果: