目錄
1.?Selenium
1.1?Selenium是啥
1.2 安裝chrom Driver
1.3 selenium 使用
1.4 selenium元素定位
1.5 訪問元素信息
1.6 交互
2. Phantomjs、Chrom handless
1.?Selenium
1.1?Selenium是啥
自動化Web瀏覽器操作
主要用于Web應用程序的測試
支持多操作系統、多瀏覽器(dirver)
支持無界面瀏覽器操作(自動交互)
1.2 安裝chrome Driver
chrome deriver下載
需要注意? driver 與 chrom版本對應
1.3 selenium 使用
# (1)導入selenium
from selenium import webdriver
from selenium.webdriver.chrome.service import Service# (2) 創建瀏覽器操作對象
path = 'chromedriver.exe'
# 創建 Service 對象
service = Service(executable_path=path)
# 創建 WebDriver 對象
browser = webdriver.Chrome(service=service)# (3)訪問網站
url = 'https://www.jd.com/'
browser.get(url)
# page_source獲取網頁源碼
content = browser.page_source
print(content)
1.4 selenium元素定位
selenium3和selenium4的語法有一定不同
button = browser.find_element(By.ID, 'chat-submit-button')
button2 = browser.find_elements(By.ID, 'chat-submit-button')
ID = "id"
XPATH = "xpath"
LINK_TEXT = "link text"
PARTIAL_LINK_TEXT = "partial link text"
NAME = "name"
TAG_NAME = "tag name"
CLASS_NAME = "class name"
CSS_SELECTOR = "css selector"
button = browser.find_element(By.ID, 'chat-submit-button')button2 = browser.find_element(By.NAME, 'wd')button3 = browser.find_elements(By.TAG_NAME, 'input')button4 = driver.find_element(By.CLASS_NAME, "btn-primary")button5 = browser.find_element(By.LINK_TEXT, '直播')button6 = browser.find_element(By.PARTIAL_LINK_TEXT, '直')button7 = browser.find_elements(By.XPATH, '//button[@id="chat-submit-button"]')button8 = browser.find_element(By.CSS_SELECTOR, '#chat-submit-button')print(button)
1.5 訪問元素信息
獲取元素屬性
?? ?.get_attribute('class')
獲取元素文本
?? ?.text
獲取標簽名
?? ?.tag_name
input = browser.find_element(By.ID, 'chat-textarea')
# 獲取標簽的屬性
print(input.get_attribute('class'))
# 獲取標簽的名字
print(input.tag_name)
# 獲取元素文本
a = browser.find_element(By.LINK_TEXT,'新聞')
print(a.text)
1.6 交互
點擊:click()
輸入:send_keys()
后退操作:browser.back()
前進操作:browser.forword()
模擬JS滾動:
?? ?js='document.documentElement.scrollTop=100000'
?? ?browser.execute_script(js) 執行js代碼
獲取網頁代碼:page_source
退出:browser.quit()
2. Phantomjs、Chrome handless
無界面瀏覽器。不進行css渲染,運行效率高。
Phantomjs基本被淘汰,建議使用Chrom handless
from selenium import webdriver
from selenium.webdriver.chrome.service import Servicedef share_browser():# 替換為你的 chromedriver 路徑path = 'chromedriver.exe' # Windows 示例,如 chromedriver.exeservice = Service(executable_path=path)options = webdriver.ChromeOptions()options.add_argument('--headless') # 無頭模式options.add_argument('--disable-gpu')options.add_argument('--no-sandbox')# 創建瀏覽器實例browser = webdriver.Chrome(service=service, options=options)return browserbrowser = share_browser()url = 'https://www.baidu.com'browser.get(url)
browser.save_screenshot('baidu22.png')