Selenium 簡介

selenium 學習筆記(一)

1.selenium 的安裝

pip inatall selenium

2. 創建瀏覽器實例

driver = webdriver.Firefox() # 創建Firefox 瀏覽器實例
driver = webdriver.Chrome() # 創建Chome 瀏覽器實例

3.打開網頁

driver.get(url)

4.查找單個元素

element = driver.find_element_by_id(“country”)
element = driver.find_element_by_name(“lat”)
element = driver.find_element_by_xpath(“//div[@id=’country’]/ul”)

5.輸入內容到文本框

element.clear() # 清除文本框內容
element.send_keys(“text”) # 文本框中輸入內容
element.send_keys(Keys.RETURN) # 相當於回車

6.代碼實例:


# @author: huangyanli
# @date : 2018-05-17 22:45:35
# @QQ : 339600718
# @Email : [email protected]
# selenium 的使用(一)


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# 創建 Chrome實例
driver = webdriver.Chrome()
# 打開網址
driver.get("https://www.zara.cn/cn/zh/z-stores-l1404.html?v1=11108")
# 找到id=store-locator-location 的元素
elem = driver.find_element_by_id("store-locator-location")
# 在elem(輸入框)中輸入“天津”
elem.send_keys("天津")
# 回車
elem.send_keys(Keys.RETURN)
print("kaishi")
# 由於網頁打開速度慢,休眠5秒,再繼續
time.sleep(5)
# 根據xpath找到相應元素
rs = driver.find_elements_by_xpath("//ul[@class='_resultList']/li")
# rs 是list,輸出時用for 循環
for i in rs:
    # 打印i 的文本信息
    print(i.text)
driver.close()

網站:
這裏寫圖片描述

運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章