一、基本使用
selenium 的基本使用步驟:
- 打開(kāi)瀏覽器;
- 獲取瀏覽器頁(yè)面的特定內(nèi)容;
- 控制瀏覽器頁(yè)面上的控件,如向一個(gè)文本框中輸入一個(gè)字符串;
- 關(guān)閉瀏覽器。
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as ec browser = webdriver.Chrome() try : browser.get( 'https://www.jd.com' ) input_t = browser.find_element_by_id( 'key' ) input_t.send_keys( 'python爬蟲' ) input_t.send_keys(Keys.ENTER) # 模擬按下Enter鍵位 wait = WebDriverWait(browser, 4 ) # 設(shè)置最長(zhǎng)等待時(shí)間4秒 wait.until(ec.presence_of_all_elements_located((By. ID , 'J_goodsList' ))) print (browser.title) # 顯示搜索頁(yè)面的標(biāo)題 print (browser.current_url) print (browser.page_source) browser.close() except Exception as e: print (e) browser.close() |
二、查找節(jié)點(diǎn)
2.1 查找單個(gè)節(jié)點(diǎn)
html 源碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >表單</ title > </ head > < body > < script > function onclick_form(){ alert(document.getElementById('name').value + document.getElementById('age').value + document.getElementsByName('country')[0].value+ document.getElementsByClassName('myclass')[0].value) } </ script > 姓名:< input id = "name" >< p ></ p > 年齡:< input id = "age" >< p ></ p > 國(guó)家:< input name = "country" >< p ></ p > 收入:< input class = "myclass" >< p ></ p > < button onclick = "onclick_form()" >提交</ button > </ body > </ html > |
樣式如下圖所示:
python 代碼自動(dòng)填充上圖中的表單:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
from selenium import webdriver from selenium.webdriver.common.by import By # 不支持本地網(wǎng)頁(yè) browser = webdriver.Chrome() try: # 這里我是用flask自己搭建的一個(gè)服務(wù) 訪問(wèn)該頁(yè)面即可打開(kāi)demo.html browser.get('http://127.0.0.1:5000/') input_t = browser.find_element_by_id('name') # 通過(guò)id屬性查找姓名input節(jié)點(diǎn) input_t.send_keys('Amo') # 自動(dòng)輸入 input_t = browser.find_element_by_id('age') input_t.send_keys('18') input_t = browser.find_element_by_name('country') # 通過(guò)name屬性查找國(guó)家input節(jié)點(diǎn) input_t.send_keys('中國(guó)') # 通過(guò)class屬性查找收入input節(jié)點(diǎn) input_t = browser.find_element_by_class_name('myclass') input_t.send_keys('1850') # 或下面的代碼 input_t = browser.find_element(By.CLASS_NAME, 'myclass') # 要想覆蓋前面的輸入,需要清空input節(jié)點(diǎn),否則會(huì)在input節(jié)點(diǎn)原來(lái)的內(nèi)容后面追加新內(nèi)容 input_t.clear() input_t.send_keys('3500') except Exception as e: print(e) browser.close() |
效果如下圖所示:
2.2 查找多個(gè)節(jié)點(diǎn)
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from selenium import webdriver from selenium.webdriver.common.by import By # 不支持本地網(wǎng)頁(yè) browser = webdriver.Chrome() try : browser.get( 'https://www.jd.com' ) # 打開(kāi)京東 # 根據(jù)節(jié)點(diǎn)名查找所有名為li的節(jié)點(diǎn) li_list = browser.find_elements_by_tag_name( 'li' ) # 輸出節(jié)點(diǎn)本身 print (li_list) print ( len (li_list)) print (li_list[ 0 ].text) ul = browser.find_elements(By.TAG_NAME, 'ul' ) print (ul) print (ul[ 0 ].text) browser.close() except Exception as e: print (e) browser.close() |
三、節(jié)點(diǎn)交互
使用 selenium 通過(guò)模擬瀏覽器單擊動(dòng)作循環(huán)單擊頁(yè)面上的6個(gè)按鈕,單擊每個(gè)按鈕后,按鈕下方的 div 就會(huì)按照按鈕的背景顏色設(shè)置 div 的背景色。
demo1.html 靜態(tài)頁(yè)面代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >彩色按鈕</ title > </ head > < body > < script > function onclick_color(e) { document.getElementById("bgcolor").style.background = e.style.background } </ script > < button class = "mybutton" style = "background: red" onclick = "onclick_color(this)" >按鈕1</ button > < button class = "mybutton" style = "background: blue" onclick = "onclick_color(this)" >按鈕2</ button > < button class = "mybutton" style = "background: yellow" onclick = "onclick_color(this)" >按鈕3</ button > < br > < button class = "mybutton" style = "background: green" onclick = "onclick_color(this)" >按鈕4</ button > < button class = "mybutton" style = "background: blueviolet" onclick = "onclick_color(this)" >按鈕5</ button > < button class = "mybutton" style = "background: gold" onclick = "onclick_color(this)" >按鈕6</ button > < p ></ p > < div id = "bgcolor" style = "width: 200px; height: 200px" > </ div > </ body > </ html > |
然后使用 Python 代碼模擬瀏覽器的單擊動(dòng)作自動(dòng)單擊頁(yè)面上的 6 個(gè)按鈕。P
ython 代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from selenium import webdriver import time browser = webdriver.Chrome() try : browser.get( 'http://127.0.0.1:5000/' ) buttons = browser.find_elements_by_class_name( 'mybutton' ) i = 0 while True : buttons[i].click() time.sleep( 1 ) i + = 1 if i = = len (buttons): i = 0 except Exception as e: print (e) browser.close() |
四、動(dòng)作鏈
使用 selenium 動(dòng)作鏈的 move_to_element 方法模擬鼠標(biāo)移動(dòng)的動(dòng)作,自動(dòng)顯示京東商城首頁(yè)左側(cè)的每個(gè)二級(jí)導(dǎo)航菜單。
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from selenium import webdriver from selenium.webdriver import ActionChains import time browser = webdriver.Chrome() try : browser.get( 'https://www.jd.com' ) actions = ActionChains(browser) li_list = browser.find_elements_by_css_selector( ".cate_menu_item" ) for li in li_list: actions.move_to_element(li).perform() time.sleep( 1 ) except Exception as e: print (e) browser.close() |
使用 selenium 動(dòng)作鏈的 drag_and_drop 方法將一個(gè)節(jié)點(diǎn)拖動(dòng)到另外一個(gè)節(jié)點(diǎn)上。
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from selenium import webdriver from selenium.webdriver import ActionChains browser = webdriver.Chrome() try : browser.get( 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' ) browser.switch_to.frame( 'iframeResult' ) source = browser.find_element_by_css_selector( '#draggable' ) target = browser.find_element_by_css_selector( '#droppable' ) actions = ActionChains(browser) actions.drag_and_drop(source, target) actions.perform() except Exception as e: print (e) browser.close() |
五、執(zhí)行 JavaScript 代碼
使用 selenium 的 execute_script 方法讓京東商城首頁(yè)滾動(dòng)到最低端,然后彈出一個(gè)對(duì)話框。示
例代碼如下:
1
2
3
4
5
|
from selenium import webdriver browser = webdriver.Chrome() browser.get( 'https://www.jd.com' ) browser.execute_script( 'window.scrollTo(0,document.body.scrollHeight)' ) browser.execute_async_script( 'alert("已經(jīng)到達(dá)頁(yè)面底端")' ) |
六、獲取節(jié)點(diǎn)信息
使用 selenium 的 API 獲取京東商城首頁(yè) HTML 代碼中 id 為 navitems-group1 的 ul 節(jié)點(diǎn)的相關(guān)信息以及 ul 節(jié)點(diǎn)中 li 子節(jié)點(diǎn)的相關(guān)信息。
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument( 'headless' ) browser = webdriver.Chrome(chrome_options = options) # browser = webdriver.PhantomJS('./webdriver/phantomjs') browser.get( 'https://www.jd.com' ) ul = browser.find_element_by_id( "navitems-group1" ) print (ul.text) print ( 'id' , '=' , ul. id ) # 內(nèi)部id,不是節(jié)點(diǎn)id屬性值 print ( 'location' , '=' , ul.location) print ( 'tag_name' , '=' , ul.tag_name) print ( 'size' , '=' , ul.size) li_list = ul.find_elements_by_tag_name( "li" ) for li in li_list: print ( type (li)) # 屬性沒(méi)找到,返回None print ( '<' , li.text, '>' , 'class=' , li.get_attribute( 'class' )) a = li.find_element_by_tag_name( 'a' ) print ( 'href' , '=' , a.get_attribute( 'href' )) browser.close() |
執(zhí)行結(jié)果如下:
秒殺
優(yōu)惠券
PLUS會(huì)員
品牌閃購(gòu)
id = 6bb622fb-df60-4619-a373-b55e44dc27af
location = {'x': 203, 'y': 131}
tag_name = ul
size = {'height': 40, 'width': 294}
<class 'selenium.webdriver.remote.webelement.WebElement'>
< 秒殺 > class= fore1
href = https://miaosha.jd.com/
<class 'selenium.webdriver.remote.webelement.WebElement'>
< 優(yōu)惠券 > class= fore2
href = https://a.jd.com/
<class 'selenium.webdriver.remote.webelement.WebElement'>
< PLUS會(huì)員 > class= fore3
href = https://plus.jd.com/index?flow_system=appicon&flow_entrance=appicon11&flow_channel=pc
<class 'selenium.webdriver.remote.webelement.WebElement'>
< 品牌閃購(gòu) > class= fore4
href = https://red.jd.com/
七、管理 Cookies
使用 selenium API 獲取 cookie 列表,并添加新的 cookie,以及刪除所有的 cookie。
示例代碼如下:
1
2
3
4
5
6
7
8
9
|
from selenium import webdriver browser = webdriver.Chrome() browser.get( 'https://www.jd.com' ) print (browser.get_cookies()) browser.add_cookie({ 'name' : 'name' , 'value' : 'jd' , 'domain' : 'www.jd.com' }) print (browser.get_cookies()) browser.delete_all_cookies() print (browser.get_cookies()) # 大部分刪除了,可能還剩下一些 |
八、改變節(jié)點(diǎn)屬性的值
通過(guò) javascript 代碼改變百度搜索按鈕的位置,讓這個(gè)按鈕在多個(gè)位置之間移動(dòng),時(shí)間間隔是2秒。
示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
from selenium import webdriver import time driver = webdriver.Chrome() driver.get( "http://www.baidu.com" ) search_button = driver.find_element_by_id( "su" ) # 百度搜索按鈕 # arguments[0]對(duì)應(yīng)的是第一個(gè)參數(shù),可以理解為python里的%s傳參,與之類似 x_positions = [ 50 , 90 , 130 , 170 ] y_positions = [ 100 , 120 , 160 , 90 ] for i in range ( len (x_positions)): js = ''' arguments[0].style.position = "absolute"; arguments[0].style.left="{}px"; arguments[0].style.top="{}px"; ''' . format (x_positions[i], y_positions[i]) driver.execute_script(js, search_button) time.sleep( 2 ) |
使用 javascript 代碼修改京東商城首頁(yè)頂端的前兩個(gè)導(dǎo)航菜單的文本和鏈接,分別改成 ‘3天極速掌握 Scala 語(yǔ)言:First Day' 和 ‘數(shù)據(jù)倉(cāng)庫(kù) Hive 從入門到小牛(一)',導(dǎo)航鏈接也會(huì)發(fā)生改變。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from selenium import webdriver driver = webdriver.Chrome() driver.get( "https://www.jd.com" ) ul = driver.find_element_by_id( 'navitems-group1' ) li_list = ul.find_elements_by_tag_name( 'li' ) a1 = li_list[ 0 ].find_element_by_tag_name( 'a' ) a2 = li_list[ 1 ].find_element_by_tag_name( 'a' ) js = ''' arguments[0].text = '3天極速掌握 Scala 語(yǔ)言:First Day' arguments[0].href = 'https://blog.csdn.net/xw1680/article/details/118743183' arguments[1].text = '數(shù)據(jù)倉(cāng)庫(kù) Hive 從入門到小牛(一)' arguments[1].href = 'https://blog.csdn.net/xw1680/article/details/118675528' ''' driver.execute_script(js, a1, a2) |
效果如下圖所示:
到此這篇關(guān)于教你快速上手Selenium爬蟲,萬(wàn)物皆可爬的文章就介紹到這了,更多相關(guān)Selenium爬蟲內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/xw1680/article/details/118931255