教你快速上手Selenium爬蟲,萬物皆可爬
一、基本使用
selenium 的基本使用步驟:
- 打開瀏覽器;
- 獲取瀏覽器頁面的特定內(nèi)容;
- 控制瀏覽器頁面上的控件,如向一個(gè)文本框中輸入一個(gè)字符串;
- 關(guān)閉瀏覽器。
示例:
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) # 顯示搜索頁面的標(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 源碼如下:
<!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)填充上圖中的表單:
from selenium import webdriver from selenium.webdriver.common.by import By # 不支持本地網(wǎng)頁 browser = webdriver.Chrome() try: # 這里我是用flask自己搭建的一個(gè)服務(wù) 訪問該頁面即可打開demo.html browser.get('http://127.0.0.1:5000/') input_t = browser.find_element_by_id('name') # 通過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') # 通過name屬性查找國(guó)家input節(jié)點(diǎn) input_t.send_keys('中國(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)原來的內(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)
示例代碼如下:
from selenium import webdriver from selenium.webdriver.common.by import By # 不支持本地網(wǎng)頁 browser = webdriver.Chrome() try: browser.get('https://www.jd.com') # 打開京東 # 根據(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 通過模擬瀏覽器單擊動(dòng)作循環(huán)單擊頁面上的6個(gè)按鈕,單擊每個(gè)按鈕后,按鈕下方的 div 就會(huì)按照按鈕的背景顏色設(shè)置 div 的背景色。
demo1.html 靜態(tài)頁面代碼如下:
<!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)單擊頁面上的 6 個(gè)按鈕。P
ython 代碼如下所示:
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)顯示京東商城首頁左側(cè)的每個(gè)二級(jí)導(dǎo)航菜單。
示例代碼如下:
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)上。
示例代碼如下:
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 方法讓京東商城首頁滾動(dòng)到最低端,然后彈出一個(gè)對(duì)話框。示
例代碼如下:
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á)頁面底端")')
六、獲取節(jié)點(diǎn)信息
使用 selenium 的 API 獲取京東商城首頁 HTML 代碼中 id 為 navitems-group1 的 ul 節(jié)點(diǎn)的相關(guān)信息以及 ul 節(jié)點(diǎn)中 li 子節(jié)點(diǎn)的相關(guān)信息。
示例代碼如下:
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)) # 屬性沒找到,返回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。
示例代碼如下:
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)屬性的值
通過 javascript 代碼改變百度搜索按鈕的位置,讓這個(gè)按鈕在多個(gè)位置之間移動(dòng),時(shí)間間隔是2秒。
示例代碼如下:
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 代碼修改京東商城首頁頂端的前兩個(gè)導(dǎo)航菜單的文本和鏈接,分別改成 ‘3天極速掌握 Scala 語言:First Day' 和 ‘?dāng)?shù)據(jù)倉庫 Hive 從入門到小牛(一)',導(dǎo)航鏈接也會(huì)發(fā)生改變。
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 語言:First Day' arguments[0]. arguments[1].text = '數(shù)據(jù)倉庫 Hive 從入門到小牛(一)' arguments[1]. ''' driver.execute_script(js, a1, a2)
效果如下圖所示:
到此這篇關(guān)于教你快速上手Selenium爬蟲,萬物皆可爬的文章就介紹到這了,更多相關(guān)Selenium爬蟲內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python爬取三國(guó)演義的實(shí)現(xiàn)方法
這篇文章通過實(shí)例給大家演示了利用python如何爬取三國(guó)演義,對(duì)于學(xué)習(xí)python的朋友們來說是個(gè)不錯(cuò)的實(shí)例,有需要的朋友可以參考借鑒,下面來一起看看吧。2016-09-09Python面向?qū)ο笾惡蛯?duì)象實(shí)例詳解
這篇文章主要介紹了Python面向?qū)ο笾惡蛯?duì)象,結(jié)合實(shí)例形式詳細(xì)分析了Python面向?qū)ο笙嚓P(guān)的繼承、多態(tài)、類及對(duì)象等概念、原理、操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-12-12Python Tkinter 簡(jiǎn)單登錄界面的實(shí)現(xiàn)
今天小編就為大家分享一篇Python Tkinter 簡(jiǎn)單登錄界面的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python打包文件執(zhí)行報(bào)錯(cuò):ModuleNotFoundError: No module 
這篇文章給大家介紹了Python打包文件執(zhí)行報(bào)錯(cuò):ModuleNotFoundError: No module named ‘pymssql‘的解決方法,如果有遇到相同問題的朋友可以參考閱讀一下本文2023-10-10OpenCV-Python實(shí)現(xiàn)腐蝕與膨脹的實(shí)例
形態(tài)學(xué)操作主要包含:腐蝕,膨脹,開運(yùn)算,閉運(yùn)算,形態(tài)學(xué)梯度運(yùn)算,頂帽運(yùn)算,黑帽運(yùn)算等操作,本文主要介紹了腐蝕與膨脹,感興趣的小伙伴們可以參考一下2021-06-06python實(shí)現(xiàn)模擬器爬取抖音評(píng)論數(shù)據(jù)的示例代碼
這篇文章主要介紹了python實(shí)現(xiàn)模擬器爬取抖音評(píng)論數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01