windows上Chrome和Firefox的安裝及使用介紹

在github或國內鏡像上下載對應的執行文件,http://chromedriver.storage.googleapis.com/index.html。
把chromedriver.exe或geckodriver.exe 放在Python解釋器的Scripts路徑下即可,比如我的:C:\b_my_python_environment\python3.7.4\Scripts,就這麼簡單!連環境變量都不需要搞,你使用的解釋器只有一個就可以這麼做,pycharm也要用這個解釋器,因爲底層使用python終端交互命令使用python3.7.4解釋器的時候也是調用Scripts下的包。

當然搞環境變量也沒問題,解決問題的方法我那種比較簡單而已。
附上檢驗代碼:

# 在開發時候, 都是使用帶有界面, 上線時候, 就使用不帶界面的

from selenium import webdriver
from selenium.webdriver.common.by import By

import time


driver = webdriver.Chrome()
#driver = webdriver.Firefox() # selenium操作火狐的命令和chrome一樣,除了這個指定的代碼。
driver.get('http://www.baidu.com')
# 根據ID定位
# input = driver.find_element_by_id('kw')
# 根據xpath定位元素
input = driver.find_element_by_xpath('//*[@id="kw"]')
print(input.tag_name) # 獲取標籤名
print(input.get_attribute('name')) # 獲取name屬性
# 根據鏈接文本定位
xinwen = driver.find_element_by_link_text('新聞')
print(xinwen.get_attribute('href'))
print(xinwen.text) # 獲取標籤中的文本

# 根據部分鏈接文本定位元素
hao123 = driver.find_element_by_partial_link_text('hao')
print(hao123.get_attribute('href'))
print(hao123.text)
# 根據css選擇定位元素
xinwen = driver.find_element_by_css_selector('#u1 > a:nth-child(1)')
print(xinwen.get_attribute('href'))
print(xinwen.text) # 獲取標籤中的文本
# 根據class名稱定位元素
xinwen = driver.find_element_by_class_name('mnav')
print(xinwen.get_attribute('href'))
print(xinwen.text) # 獲取標籤中的文本

print('_'*50)
a_s = driver.find_elements_by_class_name('mnav')
for a in a_s:
    print(a.get_attribute('href'))
    print(a.text)
# find_element與find_elements區別
# find_element: 找第一個元素, 如果沒有找到就報錯了
# find_elements: 找所有元素, 返回一個列表, 如果沒有找到返回空列表

# by_xpath的注意事項; 只能獲取標籤元素, 不能直接或文本或屬性的值
a = driver.find_element_by_xpath('//*[@id="u1"]/a[1]') # 對
# a = driver.find_element_by_xpath('//*[@id="u1"]/a[1]/text()') # 錯
# a = driver.find_element_by_xpath('//*[@id="u1"]/a[1]/@href') # 錯
print(a)

# 第二種定位元素格式(瞭解)
# a = driver.find_element(By.XPATH, '//*[@id="u1"]/a[1]')


time.sleep(10)
driver.quit()





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