1. 程式人生 > >Python爬蟲:使用BeautifulSoup分析網頁結構注意事項

Python爬蟲:使用BeautifulSoup分析網頁結構注意事項

開始我用BeautifulSoup分析網頁時候這樣做:

#從檔案讀取html原始檔內容
with open("html.txt", "r", encoding='utf-8') as file:
    content = file.read()
    
#替換轉義字元    
map = {"&lt;" : "<",
        "&gt;" : ">",
        "&amp;" : "&",
        "&quot;" : "\"",
        "&copy;" : "©"}
for (k,
v) in map.items(): content = content.replace(k, v) #獲取網頁Tag結構 soup = BeautifulSoup(str, 'lxml')

後來發現會出現奇怪的問題,原來上面的替換多此一舉。
BeautifulSoup會將HTML的例項都轉換成Unicode編碼,而且在獲取內容時候會自動替換為字串。
所以上面的程式碼可以直接簡化為:

soup = BeautifulSoup(open("html.txt", "r", encoding='utf-8'), 'lxml')

具體例子:

from bs4 import
BeautifulSoup html_str = ''' <html><body> <div> &gt; 我們的祖國是花園 &lt;) </div> </body></html> ''' soup = BeautifulSoup(html_str, 'lxml') print(soup.div) print(soup.div.string)

輸出正常:

<div>
&gt; 我們的祖國是花園 &lt;)
</div>

> 我們的祖國是花園 <)

如果我們先對字串進行了替換,如下面這個程式:

from bs4 import BeautifulSoup  
html_str = '''
<html><body>
<div>
> 我們的祖國是花園 <)
</div>
</body></html>
'''
soup = BeautifulSoup(html_str, 'lxml')
print(soup.div)
print(soup.div.string)

輸出:

<div>
&gt; 我們的祖國是花園 
</div>

> 我們的祖國是花園 

發現<)這兩個字元會因為BeautifulSoup的容錯能力而造成丟失。