美文网首页
selenium瀏覽器自動化4 - selenium + Bea

selenium瀏覽器自動化4 - selenium + Bea

作者: Maliao | 来源:发表于2018-05-30 15:24 被阅读23次

    安裝模塊

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

    官方文檔

    如何使用

    模擬請求

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

    查看請求狀態

    r.status_code
    輸出:
    >>> 200
    

    取得請求html內容

    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,能快速尋找標籤內容,也可以透過CSS選擇器快速尋找帶有標籤屬性的內容。

    官方文檔

    如何使用

    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")
    

    小結

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

    相关文章

      网友评论

          本文标题:selenium瀏覽器自動化4 - selenium + Bea

          本文链接:https://www.haomeiwen.com/subject/yzkajftx.html