欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的爬蟲包Beautiful Soup中用正則表達(dá)式來搜索

 更新時(shí)間:2016年01月20日 11:34:02   作者:crifan  
這篇文章主要介紹了Python的爬蟲包Beautiful Soup中用正則表達(dá)式來搜索的技巧,包括使用正則表達(dá)式去搜索多種可能的關(guān)鍵字以及查找屬性值未知的標(biāo)簽等,需要的朋友可以參考下

Beautiful Soup使用時(shí),一般可以通過指定對(duì)應(yīng)的name和attrs去搜索,特定的名字和屬性,以找到所需要的部分的html代碼。

但是,有時(shí)候,會(huì)遇到,對(duì)于要處理的內(nèi)容中,其name或attr的值,有多種可能,尤其是符合某一規(guī)律,此時(shí),就無法寫成固定的值了。

所以,就可以借助正則表達(dá)式來解決此問題。
比如,

<div class="icon_col">
    <h1 class="h1user">crifan</h1>
</div>

對(duì)應(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的部分的代碼,則之前的寫法,就只能找到單個(gè)的class="h1user"的部分,剩下的兩個(gè)

class="h1user test1"

class="h1user test2"

就找不到了。

那么,此時(shí),就可以用到,BeautifulSoup中非常好用的,非常強(qiáng)大的功能:

attrs中支持正則表達(dá)式的寫法

了。

就可以寫成:

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">

之類的標(biāo)簽,xxx的內(nèi)容未知(可變)的前提下

想要查找到對(duì)應(yīng)的此div標(biāo)簽,之前不知道如何實(shí)現(xiàn)。
如果寫成:

sopu.findAll("div", attrs={"aria-lable": "xxx"});

則xxx必須寫出來,如果不寫出來屬性值,也就沒法用上attrs了,就沒法實(shí)現(xiàn)此處查找特性屬性值的標(biāo)簽了。
所以針對(duì):

<div aria-label="5星, 747 份評(píng)分" 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 份評(píng)分
 </span>
</div>

可以通過:

soup.findAll("div", attrs={"aria-lable": True});

去查找到屬性包含aria-lable的div標(biāo)簽的。

所以,對(duì)于上面的,之前不知道如何處理:

用BeautifulSoup查找未知屬性值,但是已知屬性的名字的標(biāo)簽

則此處,就可以針對(duì):

<div aria-lable="xxx">

去用:

sopu.findAll("div", attrs={"aria-lable": True});

就可以查找到對(duì)應(yīng)的包含屬性aria-lable的div標(biāo)簽了。

相關(guān)文章

最新評(píng)論