Python的爬蟲包Beautiful Soup中用正則表達式來搜索
Beautiful Soup使用時,一般可以通過指定對應(yīng)的name和attrs去搜索,特定的名字和屬性,以找到所需要的部分的html代碼。
但是,有時候,會遇到,對于要處理的內(nèi)容中,其name或attr的值,有多種可能,尤其是符合某一規(guī)律,此時,就無法寫成固定的值了。
所以,就可以借助正則表達式來解決此問題。
比如,
<div class="icon_col"> <h1 class="h1user">crifan</h1> </div>
對應(yīng)的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">
想要查找到對應(yīng)的此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});
就可以查找到對應(yīng)的包含屬性aria-lable的div標簽了。
相關(guān)文章
運用TensorFlow進行簡單實現(xiàn)線性回歸、梯度下降示例
這篇文章主要介紹了運用TensorFlow進行簡單實現(xiàn)線性回歸、梯度下降示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03Pytorch使用VGG16模型進行預(yù)測貓狗二分類實戰(zhàn)
VGG16是Visual Geometry Group的縮寫,它的名字來源于提出該網(wǎng)絡(luò)的實驗室,本文我們將使用PyTorch來實現(xiàn)VGG16網(wǎng)絡(luò),用于貓狗預(yù)測的二分類任務(wù),我們將對VGG16的網(wǎng)絡(luò)結(jié)構(gòu)進行適當?shù)男薷?以適應(yīng)我們的任務(wù),需要的朋友可以參考下2023-08-08Python偏函數(shù)Partial function使用方法實例詳解
這篇文章主要介紹了Python偏函數(shù)Partial function使用方法實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06