python高級爬蟲筆記(1)

寫在前面

selenium 雖然是新手友好型的爬蟲工具,但是個人覺得絕對不是適合新手入門的爬蟲。
推薦在瞭解了 requests體系 的爬蟲,有了爬蟲的一些常識之後,再來看selenium。

事實上,requests體系的爬蟲已經足夠滿足現階段大多數網站的爬蟲需求

關於Selenium

Selenium誕生於2014年,創造者是ThoughtWorks公司的測試工程師Jason Huggins。創造Selenium的目的就是做自動化測試,用以檢測網頁交互,避免重複勞動。
這個工具可以用來自動加載網頁,供爬蟲抓取數據。

官方文檔

安裝

  1. 這裏下載chromedriver
    注意:與目前正在使用的Chrome版本相一致
    補充:對於macOS用戶,可以把該文件放到 /usr/local/bin/ 目錄下,可以省去一些的配置煩惱
  2. pip install selenium

使用

  1. 設置配置
    option = webdriver.ChromeOptions()
    option.add_argument(‘headless’)
  2. 添加驅動
    driver = webdriver.Chrome(chrome_options=option)

牛刀小試

# 與百度首頁交互

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

option = webdriver.ChromeOptions()
# option.add_argument('headless')

# 要換成適應自己操作系統的chromedriver
driver = webdriver.Chrome(chrome_options=option)


url = 'https://www.baidu.com'

# 打開網站
driver.get(url)

# 打印當前頁面標題
print(driver.title)

# 在搜索框中輸入文字
timeout = 5
search_content = WebDriverWait(driver, timeout).until(
    # lambda d: d.find_element_by_xpath('//input[@id="kw"]')
    EC.presence_of_element_located((By.XPATH, '//input[@id="kw"]'))
)
search_content.send_keys('python')

import time
time.sleep(3)

# 模擬點擊“百度一下”
search_button = WebDriverWait(driver, timeout).until(
    lambda d: d.find_element_by_xpath('//input[@id="su"]'))
search_button.click()

# 打印搜索結果
search_results = WebDriverWait(driver, timeout).until(
    # lambda d: d.find_elements_by_xpath('//h3[@class="t c-title-en"] | //h3[@class="t"]')
    lambda e: e.find_elements_by_xpath('//h3[contains(@class,"t")]/a[1]')
)
# print(search_results)

for item in search_results:
    print(item.text)

driver.close()
/usr/local/Caskroom/miniconda/base/envs/scikit/lib/python3.7/site-packages/ipykernel_launcher.py:13: DeprecationWarning: use options instead of chrome_options
  del sys.path[0]


百度一下,你就知道
python每天免費網上學習python
Welcome to Python.org
Python_百度百科
Python 基礎教程 | 菜鳥教程
Download Python | Python.org
Python教程 - 廖雪峯的官方網站
Python_官方電腦版_華軍純淨下載
我們生活在“Python時代”
Python 簡介 | 菜鳥教程
Python - 知乎
Python基礎教程,Python入門教程(非常詳細)
英特爾_Python_發行版
喚境_不懂編程不會美術_也能輕鬆製作遊戲
免費全能的寶塔Linux面板_一鍵管理服務器

頁面交互方法

# 查找元素:
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")

# 輸入文字:
element.send_keys("some text")

# 點擊
element.click()

# 動作鏈
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()

# 在頁面間切換
window_handles = driver.window_handles
driver.switch_to.window(window_handles[-1])

# 保存網頁截圖
driver.save_screenshot('screen.png')

定位元素

# 查找一個元素
find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

# 查找多個元素
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

# 通過id定位

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
  </form>
 </body>
<html>

login_form = driver.find_element_by_id('loginForm')

# 通過name定位

<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>

username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')

# 通過鏈接文本定位

<html>
 <body>
  <p>Are you sure you want to do this?</p>
  <a href="continue.html">Continue</a>
  <a href="cancel.html">Cancel</a>
</body>
<html>

continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

# 通過標籤名定位

<html>
 <body>
  <h1>Welcome</h1>
  <p>Site content goes here.</p>
</body>
<html>

heading1 = driver.find_element_by_tag_name('h1')

# 通過類名定位

<html>
 <body>
  <p class="content">Site content goes here.</p>
</body>
<html>

content = driver.find_element_by_class_name('content')

# 通過CSS選擇器定位

<html>
 <body>
  <p class="content">Site content goes here.</p>
</body>
<html>

content = driver.find_element_by_css_selector('p.content')

# 兩個私有方法
from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, '//button[text()="Some text"]')
driver.find_elements(By.XPATH, '//button')

By後面可以用來定位的屬性
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"

# 推薦使用xpath定位
username = driver.find_element_by_xpath("//form[input/@name='username']")
username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
username = driver.find_element_by_xpath("//input[@name='username']")

# 推薦使用鏈接文本定位
continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

關於元素的定位

推薦使用 katalon ,該軟件開啓之後,可以記錄瀏覽器的點擊記錄,進而一鍵生成selenium模擬點擊的代碼


同時,通過瀏覽器的元素審查功能,在要定位的元素上右鍵,大部分瀏覽器都有直接複製xpath的功能

個人使用體會

優點:

  • 新手友好,操作方便
  • 天生適合爬取動態加載的頁面
  • 截圖功能非常強大
  • cookies的存取十分方便,與requests搭配堪稱邪教

缺點:

  • 初始安裝過程繁雜
  • 速度慢,效率低
  • 內存佔用大
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章