selenium瀏覽器自動化4 - selenium + Beautiful Soup

安裝模塊

selenium
requests
beautifulsoup4
  1. selenium
    主要用於登入或js互動,剩餘的在使用bs4進行爬取。
  1. requests
    能模擬http請求,如:get、post、put、delete,通常是爬取分頁或a標籤時用到。

官方文檔

如何使用

模擬請求

r = requests.get('https://api.github.com/events')

查看請求狀態(tài)

r.status_code
輸出:
>>> 200

取得請求html內(nèi)容

r.text
輸出:
>>> '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="zh-TW"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" ...</html>'
  1. Beautiful Soup
    Beautiful Soup能解析html,能快速尋找標籤內(nèi)容,也可以透過CSS選擇器快速尋找?guī)в袠嘶`屬性的內(nèi)容。

官方文檔

如何使用

from bs4 import BeautifulSoup
import requests
web_data = requests.get('https://api.github.com/events')
soup = BeautifulSoup(web_data, 'lxml') #解析Html
soup.title

啟動

基本使用

selenium_bs4_demo1.py

from bs4 import BeautifulSoup

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://w3.iiiedu.org.tw/')
wb_html = browser.page_source
soup = BeautifulSoup(wb_html,"lxml")

小結(jié)

大部分網(wǎng)頁都用requests都能獲取,用到selenium情況比較少,有登入或js需求可以參考,在此紀錄心得。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容