原文:https://blog.csdn.net/weixin_43891121/article/details/87989080
今天用BeautifulSoup解析頁面時遇到了.string返回None的問題,待解析的源碼如下:
< a
class =“bets-name” href="/stock/sh601766.html" >
中國中車( < span > 601766 < / span >)
< / a >
使用如下代碼來獲得tag中的字符串:
soup = BeautifulSoup(html, ‘html.parser’)
name = soup.find_all(‘a’, attrs={‘class’: ‘bets-name’})[0].string
這段代碼來獲得字符串時,返回的是None,不解,於是去查了BeautifulSoup的官方文檔,發現.string方法在tag包含多個子節點時,tag無法確定.string方法應該調用哪個子節點的內容,所以輸出None。
那么如何獲得包含在tag中的字符串呢?方法如下:
soup = BeautifulSoup(html, ‘html.parser’)
name = soup.find_all(‘a’,attrs={‘class’: ‘bets-name’})[0].text
這樣就可以得到字符串 ’ 中國中車(601766) '。不過這其中包含很多空格,只需用split方法處理即可,不再贅述。
總結:
.string可以返回當前節點中的內容,但是當前節點包含子節點時,.string不知道要獲取哪一個節點中的內容,故返回空
.text(或者.get_text())可以返回當前節點所包含的所有文本內容,包括當前節點的子孫節點