教你快速上手Selenium爬蟲,萬物皆可爬
一、基本使用
selenium 的基本使用步驟:
- 打開瀏覽器;
- 獲取瀏覽器頁面的特定內(nèi)容;
- 控制瀏覽器頁面上的控件,如向一個文本框中輸入一個字符串;
- 關(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è)置最長等待時間4秒
wait.until(ec.presence_of_all_elements_located((By.ID, 'J_goodsList')))
print(browser.title) # 顯示搜索頁面的標題
print(browser.current_url)
print(browser.page_source)
browser.close()
except Exception as e:
print(e)
browser.close()
二、查找節(jié)點
2.1 查找單個節(jié)點
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>
國家:<input name="country"><p></p>
收入:<input class="myclass"><p></p>
<button onclick="onclick_form()">提交</button>
</body>
</html>
樣式如下圖所示:

python 代碼自動填充上圖中的表單:
from selenium import webdriver
from selenium.webdriver.common.by import By
# 不支持本地網(wǎng)頁
browser = webdriver.Chrome()
try:
# 這里我是用flask自己搭建的一個服務(wù) 訪問該頁面即可打開demo.html
browser.get('http://127.0.0.1:5000/')
input_t = browser.find_element_by_id('name') # 通過id屬性查找姓名input節(jié)點
input_t.send_keys('Amo') # 自動輸入
input_t = browser.find_element_by_id('age')
input_t.send_keys('18')
input_t = browser.find_element_by_name('country') # 通過name屬性查找國家input節(jié)點
input_t.send_keys('中國')
# 通過class屬性查找收入input節(jié)點
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é)點,否則會在input節(jié)點原來的內(nèi)容后面追加新內(nèi)容
input_t.clear()
input_t.send_keys('3500')
except Exception as e:
print(e)
browser.close()
效果如下圖所示:

2.2 查找多個節(jié)點

示例代碼如下:
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é)點名查找所有名為li的節(jié)點
li_list = browser.find_elements_by_tag_name('li')
# 輸出節(jié)點本身
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é)點交互
使用 selenium 通過模擬瀏覽器單擊動作循環(huán)單擊頁面上的6個按鈕,單擊每個按鈕后,按鈕下方的 div 就會按照按鈕的背景顏色設(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 代碼模擬瀏覽器的單擊動作自動單擊頁面上的 6 個按鈕。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()
四、動作鏈
使用 selenium 動作鏈的 move_to_element 方法模擬鼠標移動的動作,自動顯示京東商城首頁左側(cè)的每個二級導(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 動作鏈的 drag_and_drop 方法將一個節(jié)點拖動到另外一個節(jié)點上。
示例代碼如下:
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 方法讓京東商城首頁滾動到最低端,然后彈出一個對話框。示
例代碼如下:
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)到達頁面底端")')
六、獲取節(jié)點信息
使用 selenium 的 API 獲取京東商城首頁 HTML 代碼中 id 為 navitems-group1 的 ul 節(jié)點的相關(guān)信息以及 ul 節(jié)點中 li 子節(jié)點的相關(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é)點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會員
品牌閃購
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會員 > class= fore3
href = https://plus.jd.com/index?flow_system=appicon&flow_entrance=appicon11&flow_channel=pc
<class 'selenium.webdriver.remote.webelement.WebElement'>
< 品牌閃購 > 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é)點屬性的值
通過 javascript 代碼改變百度搜索按鈕的位置,讓這個按鈕在多個位置之間移動,時間間隔是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]對應(yīng)的是第一個參數(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 代碼修改京東商城首頁頂端的前兩個導(dǎo)航菜單的文本和鏈接,分別改成 ‘3天極速掌握 Scala 語言:First Day' 和 ‘?dāng)?shù)據(jù)倉庫 Hive 從入門到小牛(一)',導(dǎo)航鏈接也會發(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)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信