Python的爬蟲包Beautiful Soup中用正則表達式來搜索
Beautiful Soup使用時,一般可以通過指定對應的name和attrs去搜索,特定的名字和屬性,以找到所需要的部分的html代碼。
但是,有時候,會遇到,對于要處理的內(nèi)容中,其name或attr的值,有多種可能,尤其是符合某一規(guī)律,此時,就無法寫成固定的值了。
所以,就可以借助正則表達式來解決此問題。
比如,
<div class="icon_col">
<h1 class="h1user">crifan</h1>
</div>
對應的BeautifulSoup代碼如下:
h1userSoup = soup.find(name="h1", attrs={"class":"h1user"});
而如果html是這種:
<div class="icon_col">
<h1 class="h1user">crifan</h1>
<h1 class="h1user test1">crifan 123</h1>
<h1 class="h1user test2">crifan 456</h1>
</div>
那么想要一次性地找到所有的,符合條件的h1的部分的代碼,則之前的寫法,就只能找到單個的class="h1user"的部分,剩下的兩個
class="h1user test1"
和
class="h1user test2"
就找不到了。
那么,此時,就可以用到,BeautifulSoup中非常好用的,非常強大的功能:
attrs中支持正則表達式的寫法
了。
就可以寫成:
h1userSoupList = soup.findAll(name="h1", attrs={"class":re.compile(r"h1user(\s\w+)?")});
就可以一次性地,找到:
class="h1user" class="h1user test1" class="h1user test2"
了。
<div aria-lable="xxx">
想要查找到對應的此div標簽,之前不知道如何實現(xiàn)。
如果寫成:
sopu.findAll("div", attrs={"aria-lable": "xxx"});
則xxx必須寫出來,如果不寫出來屬性值,也就沒法用上attrs了,就沒法實現(xiàn)此處查找特性屬性值的標簽了。
所以針對:
<div aria-label="5星, 747 份評分" class="rating" role="img" tabindex="-1"> <div> <span class="rating-star"> </span> <span class="rating-star"> </span> <span class="rating-star"> </span> <span class="rating-star"> </span> <span class="rating-star"> </span> </div> <span class="rating-count"> 747 份評分 </span> </div>
可以通過:
soup.findAll("div", attrs={"aria-lable": True});
去查找到屬性包含aria-lable的div標簽的。
所以,對于上面的,之前不知道如何處理:
用BeautifulSoup查找未知屬性值,但是已知屬性的名字的標簽
則此處,就可以針對:
<div aria-lable="xxx">
去用:
sopu.findAll("div", attrs={"aria-lable": True});
就可以查找到對應的包含屬性aria-lable的div標簽了。
相關文章
對Python 兩大環(huán)境管理神器 pyenv 和 virtualenv詳解
今天小編就為大家分享一篇對Python 兩大環(huán)境管理神器 pyenv 和 virtualenv詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python OpenCV學習筆記直方圖反向投影的實現(xiàn)
這篇文章主要介紹了python OpenCV學習筆記直方圖反向投影的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
python爬蟲項目設置一個中斷重連的程序的實現(xiàn)
這篇文章主要介紹了python爬蟲項目設置一個中斷重連的程序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
PyCharm安裝配置Qt Designer+PyUIC圖文教程
這篇文章主要介紹了PyCharm安裝配置Qt Designer+PyUIC圖文教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05

