Python的爬虫包Beautiful Soup中用正则表达式来搜索

yipeiwu_com5年前Python爬虫

Beautiful Soup使用时,一般可以通过指定对应的name和attrs去搜索,特定的名字和属性,以找到所需要的部分的html代码。

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

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

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

之类的标签,xxx的内容未知(可变)的前提下

想要查找到对应的此div标签,之前不知道如何实现。
如果写成:

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

则xxx必须写出来,如果不写出来属性值,也就没法用上attrs了,就没法实现此处查找特性属性值的标签了。
所以针对:

<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爬取微博数据生成词云图片实例代码

利用Python爬取微博数据生成词云图片实例代码

前言 在很早之前写过一篇怎么利用微博数据制作词云图片出来,之前的写得不完整,而且只能使用自己的数据,现在重新整理了一下,任何的微博数据都可以制作出来,一年一度的虐汪节,是继续蹲在角落默默...

深入剖析Python的爬虫框架Scrapy的结构与运作流程

深入剖析Python的爬虫框架Scrapy的结构与运作流程

网络爬虫(Web Crawler, Spider)就是一个在网络上乱爬的机器人。当然它通常并不是一个实体的机器人,因为网络本身也是虚拟的东西,所以这个“机器人”其实也就是一段程序,并且它...

Python爬虫DOTA排行榜爬取实例(分享)

Python爬虫DOTA排行榜爬取实例(分享)

1、分析网站 打开开发者工具,我们观察到排行榜的数据并没有在doc里   doc文档 在Javascript里我么可以看到下面代码: ajax的post方法异步请求数据 在...

python爬虫之urllib3的使用示例

Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库。许多Python的原生系统已经开始使用urllib3。Urllib3提供了很多python标准库urllib里...

python通过伪装头部数据抵抗反爬虫的实例

0x00 环境 系统环境:win10 编写工具:JetBrains PyCharm Community Edition 2017.1.2 x64 python 版本:python-3.6...