Python使用BeautifulSoup4修改網頁內容的實戰記錄

最近有個小項目,需要爬取頁面上相應的資源數據後,保存到本地,然後將原始的HTML源文件保存下來,對HTML頁面的內容進行修改將某些標簽整個給替換掉。

對於這類需要對HTML進行操作的需求,最方便的莫過於 BeautifulSoup4 的庫瞭。

樣例的HTML代碼如下:

<html>
<body>
    <a class="videoslide" href="http://www.test.com/wp-content/uploads/1020/1381824922.JPG" rel="external nofollow"  rel="external nofollow" >
       <img src="http://www.test.com/wp-content/uploads/1020/1381824922_zy_compress.JPG" data-zy-media-id="zy_location_201310151613422786"/>
    </a>
    <a href="http://www.test.com/wp-content/uploads/1020/第一張_1381824798.JPG" rel="external nofollow"  rel="external nofollow" >
       <img data-zy-media-id="zy_image_201310151613169945" src="http://www.test.com/wp-content/uploads/1020/第一張_1381824798_zy_compress.JPG"/></a>
    <a href="http://www.test.com/wp-content/uploads/1020/第二張_1381824796.jpg" rel="external nofollow"  rel="external nofollow" >
       <img data-zy-media-id="zy_image_201310151613163009" src="http://www.test.com/wp-content/uploads/1020/第二張_1381824796_zy_compress.jpg"/>
    </a>
    <a href="http://www.test.com/wp-content/uploads/1020/第三張.jpg" rel="external nofollow"  rel="external nofollow" >
       <img data-zy-media-id="zy_image_201312311838584446" src="http://www.test.com/wp-content/uploads/1020/第三張_zy_compress.jpg"/>
    </a>
</body>
</html>

這裡主要包括瞭 <a > 標簽, <a > 標簽裡面嵌入瞭 <img > 標簽,其中有 <a class="videoslide"> 的標識該標簽實際是可以播放動畫的。需要根據 class="videoslide" 來判斷將整個 <a > 標簽換成播放器的 <video > 標簽,將沒有 class="videoslide" 的 <a > 標簽換成 <figure> 標簽。

也就是將帶有的 <a class="videoslide" ...><img ... /></a> 標簽換成

<div class="video">
<video controls width="100%" poster="視頻鏈接的圖片地址.jpg">
    <source src="視頻文件的靜態地址.mp4" type="video/mp4" />
    您的瀏覽器不支持H5視頻,請使用Chrome/Firefox/Edge瀏覽器。
</video>
</div>

將 <a ....><img .../></a> 標簽換成

<figure>
    < img src="圖片地址_compressed.jpg" data-zy-media-id="圖片地址.jpg">
    <figcaption>文字說明(如果有)</figcaption>
</figure>

這裡通過BeautifulSoup4 的select()方法找到標簽,通過get()方法獲取標簽及標簽屬性值,通過replaceWith來替換標簽,具體代碼如下:

首先安裝BeautifulSoup4的庫,BeautifulSoup4庫依賴於lxml庫,所以也需要安裝lxml庫。

pip install bs4
pip install lxml

具體代碼實現如下:

import os
from bs4 import BeautifulSoup
htmlstr='<html><body>' \
        '<a class="videoslide" href="http://www.test.com/wp-content/uploads/1020/1381824922.JPG" rel="external nofollow"  rel="external nofollow" >' \
        '<img src="http://www.test.com/wp-content/uploads/1020/1381824922_zy_compress.JPG" data-zy-media-id="zy_location_201310151613422786"/></a>' \
        '<a href="http://www.test.com/wp-content/uploads/1020/第一張_1381824798.JPG" rel="external nofollow"  rel="external nofollow" >' \
        '<img data-zy-media-id="zy_image_201310151613169945" src="http://www.test.com/wp-content/uploads/1020/第一張_1381824798_zy_compress.JPG"/></a>' \
        '<a href="http://www.test.com/wp-content/uploads/1020/第二張_1381824796.jpg" rel="external nofollow"  rel="external nofollow" >' \
        '<img data-zy-media-id="zy_image_201310151613163009" src="http://www.test.com/wp-content/uploads/1020/第二張_1381824796_zy_compress.jpg"/></a>' \
        '<a href="http://www.test.com/wp-content/uploads/1020/第三張.jpg" rel="external nofollow"  rel="external nofollow" >' \
        '<img data-zy-media-id="zy_image_201312311838584446" src="http://www.test.com/wp-content/uploads/1020/第三張_zy_compress.jpg"/></a>' \
        '</body></html>'

def procHtml(htmlstr):
    soup = BeautifulSoup(htmlstr, 'lxml')
    a_tags=soup.select('a')
    for a_tag in a_tags:
        a_tag_src = a_tag.get('href')
        a_tag_filename = os.path.basename(a_tag_src)
        a_tag_path = os.path.join('src', a_tag_filename)
        a_tag['href']=a_tag_path
        next_tag=a_tag.next
        #判斷是視頻還是圖片,如果a標簽帶瞭class="videoslide" 是視頻否則是圖片
        if a_tag.get('class') and 'videoslide'==a_tag.get('class')[0]:
            # 處理視頻文件
            media_id = next_tag.get('data-zy-media-id')
            if media_id:
                media_url = 'http://www.test.com/travel/show_media/' + str(media_id)+'.mp4'
                media_filename = os.path.basename(media_url)
                media_path = os.path.join('src', media_filename)
                # 將div.video標簽替換a標簽
                video_html = '<div class=\"video\"><video controls width = \"100%\" poster = \"' + a_tag_path + '\" ><source src = \"' + media_path + '\" type = \"video/mp4\" /> 您的瀏覽器不支持H5視頻,請使用Chrome / Firefox / Edge瀏覽器。 </video></div>'
                video_soup = BeautifulSoup(video_html, 'lxml')
                a_tag.replaceWith(video_soup.div)
        else:
            #獲取圖片信息
            if 'img'==next_tag.name:
                img_src=next_tag.get('src')
                # 判斷是否路徑是否為本地資源 data:image和file:
                if img_src.find('data:image') == -1 and img_src.find('file:') == -1:
                    img_filename = os.path.basename(img_src)
                    img_path = os.path.join('src', img_filename)
                    # 將<figure><img>標簽替換a標簽
                    figcaption=''
                    figure_html='<figure><img src=\"'+img_path+'\" data-zy-media-id=\"'+a_tag_path+'\"><figcaption>'+figcaption+'</figcaption></figure>'
                    figure_soup = BeautifulSoup(figure_html, 'lxml')
                    a_tag.replaceWith(figure_soup.figure)
    html_content = soup.contents[0]
    return html_content

if __name__ == '__main__':
    pro_html_str=procHtml(htmlstr)
    print(pro_html_str)

結果:

<html>
<body>
<div class="video">
<video controls="" poster="src\1381824922.JPG" width="100%">
<source src="src\zy_location_201310151613422786.mp4" type="video/mp4"/> 您的瀏覽器不支持H5視頻,請使用Chrome / Firefox / Edge瀏覽器。 
</video>
</div>
<figure>
<img data-zy-media-id="src\第一張_1381824798.JPG" src="src\第一張_1381824798_zy_compress.JPG"/>
<figcaption></figcaption>
</figure>
<figure>
<img data-zy-media-id="src\第二張_1381824796.jpg" src="src\第二張_1381824796_zy_compress.jpg"/>
<figcaption></figcaption></figure>
<figure>
<img data-zy-media-id="src\第三張.jpg" src="src\第三張_zy_compress.jpg"/>
<figcaption></figcaption>
</figure>
</body>
</html>

總結 

到此這篇關於Python使用BeautifulSoup4修改網頁內容的文章就介紹到這瞭,更多相關Python BeautifulSoup4修改網頁內容內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: