您的位置:首页 > 其它

【教程】BeautifulSoup中使用正则表达式去搜索多种可能的关键字

2015-07-08 16:43 330 查看
【背景】

折腾过基本的BeautifulSoup的人,知道,可以通过指定对应的name和attrs去搜索,特定的名字和属性,以找到所需要的部分的html代码。

但是,有时候,会遇到,对于要处理的内容中,其name或attr的值,有多种可能,尤其是符合某一规律,此时,就无法写成固定的值了。

所以,就可以借助正则表达式来解决此问题。

【举例说明】

比如,原先教程:

【教程】Python中第三方的用于解析HTML的库:BeautifulSoup

中的html:
<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"
了。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: