Selenium學(xué)習(xí)003-元素選擇之BeautifulSoup4

Selenium學(xué)習(xí)筆記目錄

BeautifulSoup4

  • BS是可以從HTML或XML文件中提取數(shù)據(jù)的庫(kù)

  • Selenium可以用來(lái)遠(yuǎn)程獲取數(shù)據(jù)

  • 有的時(shí)候,感覺(jué)用Selenium獲取某些元素?cái)?shù)據(jù)不太方便

  • 可以將其父節(jié)點(diǎn)的html獲取回來(lái),利用BS在本地做分析

  • 我們可以將它和selenium兩種技術(shù)融合使用,達(dá)到我們的目的

  • 安裝BeautifulSoup4

    pip install beautifulsoup4
    # pip install beautifulsoup4 -i https://pypi.douban.com/simple/
    pip install html5lib
    
  • 常見(jiàn)用法(詳見(jiàn)示例內(nèi)的代碼及注釋)

    • 示例及具體方法
    # 本例采用的是本地的html
    with open ('test.html',encoding = 'utf8') as f :
        html_doc = f.read()
    # 導(dǎo)入beautifulsoup
    from bs4 import BeautifulSoup
    
    # 指定html5lib來(lái)解析html文檔
    soup = BeautifulSoup(html_doc,'html5lib')
    
    print(soup.title) # 獲取標(biāo)簽整體內(nèi)容
    print(soup.p)# 有多個(gè)時(shí),獲取的是第一個(gè)
    print(soup.title.name) # 獲取標(biāo)簽名稱
    print(soup.title.string) # 獲取點(diǎn)前節(jié)點(diǎn)標(biāo)簽的內(nèi)容
    print(soup.title.get_text()) # 獲取當(dāng)前節(jié)點(diǎn)及子節(jié)點(diǎn)的所有內(nèi)容
    print(soup.body.get_text("|")) # 獲取當(dāng)前節(jié)點(diǎn)及子節(jié)點(diǎn)的所有內(nèi)容,以|分隔每個(gè)節(jié)點(diǎn)的內(nèi)容
    print(soup.title.parent)# 獲取當(dāng)前節(jié)點(diǎn)及父節(jié)點(diǎn)的內(nèi)容
    
    print(soup.body['style']) # 獲取屬性值
    print(soup.body.get('style')) # 獲取屬性值
    
    # 有多個(gè)標(biāo)簽想獲取非第一個(gè)
    # 方法一;先返回所有的,在根據(jù)下標(biāo)查找
    print(soup.find_all('p')) #返回的是一個(gè)列表所以可以使用列表獲取元素的方法
    print(soup.find_all('p')[1]) # 根據(jù)下標(biāo)獲取第二個(gè)
    # 方法二:根據(jù)屬性找
    print(soup.find_all('p',id='b')) # 根據(jù)id獲取第二個(gè)
    
    # 執(zhí)行結(jié)果
    
    <title>測(cè)試</title>
    <p id="a">第一個(gè)p</p>
    title
    測(cè)試
    測(cè)試
    
    |
    標(biāo)題1
    |
    |
    標(biāo)題2
    |
    |第一個(gè)p|
    |第二個(gè)p|
    |第三個(gè)p|
    
    
    <head>
    <title>測(cè)試</title>
    </head>
    background-color: yellow
    background-color: yellow
    [<p id="a">第一個(gè)p</p>, <p id="b">第二個(gè)p</p>, <p id="c">第三個(gè)p</p>]
    <p id="b">第二個(gè)p</p>
    [<p id="b">第二個(gè)p</p>]
    
    • 演示文件
    # html文件(本地)
    <html>
    <head>
    <title>測(cè)試</title>
    </head>
    <body style='background-color: yellow'>
    <h1 >
    標(biāo)題1
    </h1>
    <h2 style = 'background-color:green;text-align:center'>
    標(biāo)題2
    </h2>
    <p id ='a'>第一個(gè)p</p>
    <p id = 'b'>第二個(gè)p</p>
    <p id = 'c'>第三個(gè)p</p>
    </body>
    </html>
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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