最新公告
  • 欢迎您光临网站无忧模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • Python爬虫学习之BeautifulSoup4的简单用法

    正文概述    2020-06-27   260

    Python爬虫学习之BeautifulSoup4的简单用法

    1 urllib和urllib2

    Python中包含了两个网络模块,分别是urllib与urllib2,urllib2是urllib的升级版,拥有更强大的功能。urllib,让我们可以像读文件一样,读取http与ftp。而urllib2,则在urllib的基础上,提供了更多的接口,如cookie、代理、认证等更强大的功能。

    这里借鉴下文章一和文章二的说法:

    urllib仅可以接受URL,不能创建,设置headers的request类实例;

    但是urllib提供urlencode()方法用来GET查询字符串的产生,而urllib2则没有(这是urllib和urllib2经常一起使用的主要原因)

    编码工作使用urllib的urlencode()函数,帮我们讲key:value这样的键值对转换成‘key=value’这样的字符串,解码工作可以使用urllib的unquote

    该两个库都是Python自带库,且由于简单爬虫所需要的功能比较少,所以不做更多赘述。

    2 BeautifulSoup

    现在的Mac已经不能用

    $ sudo easy_install pip

    来安装pip,而只能用一个get-pip.py的方法,网上有大量教程。然后安装完毕后用pip来安装beautilfulsoup4。

    安装完以后一个简单的例子(环境Python2.7,其实Python3在这段代码也差不多):

    from urllib import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://blog.orisonchan.cc")
    bsObj = BeautifulSoup(html.read())
    print(bsObj.h1)

    网页不存在的情况如何判断

    方法一:空值判断

    if html is None:
        print("URL not found")
    else:
        # expressions

    方法二:try-catch

    try:
        html = urlopen("http://blog.orisonchan.cc")
    except HTTPError as e:
        print(e)
        # expressions

    这里从O`Reilly系列图书《Python网络数据采集》中摘抄一个完整例子:

    from urllib.request import urlopen
    from urllib.error import HTTPError
    from bs4 import BeautifulSoup
    
    def getTitle(url):
        try:
            html = urlopen(url) 
        except HTTPError as e:
            return None
        try:
            bsObj = BeautifulSoup(html. read())
            title = bsObj.body.h1
        except AttributeError as e:
            return None
        return title
    
    title = getTitle(" http://www.pythonscraping.com/pages/page1.html")
    if title == None:
        print("Title could not be found")
    else:
        print(title)

    2.1 常用方法

    2.1.1 find()

    格式:

    find(name, attributes, recursive, text ,keywords)

    参数介绍

    name:标签名,如a,p。
    attributes:一个标签的若干属性和对应的属性值。
    recursive:是否递归。如果是,就会查找tag的所有子孙标签,默认true。
    text:标签的文本内容去匹配,而不是标签的属性。
    keyword:选择那些具有指定属性的标签。

    find()示例:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://blog.orisonchan.cc")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    print str(bsObj.find(name='h1', attrs={'class': {'post-title'}}))

    结果

    <h1 class="post-title" itemprop="name headline">
    <a class="post-title-link" href="/2018/08/14/43/" itemprop="url">常见“树”概念解析(1)</a></h1>

    2.1.2 find_all()

    find_all(name, attributes, recursive, text , limit, keywords)

    参数介绍

    name:标签名,如a,p。
    attributes:一个标签的若干属性和对应的属性值。
    recursive:是否递归。如果是,就会查找tag的所有子孙标签,默认true。
    text:标签的文本内容去匹配,而不是标签的属性。
    limit: 个数限制,find其实就等于limit=1,查看find源码即可发现。
    keyword:选择那些具有指定属性的标签。

    bsObj.find_all("a")可以简写为bsObj("a")

    find_all()示例:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://blog.orisonchan.cc")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    print str(bsObj.find_all(name='h1', attrs={'class': {'post-title'}})[1:3]).decode('unicode-escape')

    结果

    [<h1 class="post-title" itemprop="name headline">
    <a class="post-title-link" href="/2018/08/13/42/" itemprop="url">Spark聚合下推思路以及demo</a></h1>, 
    <h1 class="post-title" itemprop="name headline">
    <a class="post-title-link" href="/2018/08/09/41/" itemprop="url">写一个Spark DataSource的随手笔记</a></h1>]

    2.2 常用对象

    2.2.1 tag对象

    即html中的标签。其中两个属性就是name和attributes。使用如下:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://blog.orisonchan.cc")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    tag = bsObj.h1
    print(tag)
    print(tag.name)
    print(tag.attrs)
    print(tag['class'])

    结果

    <h1 class="post-title" itemprop="name headline">
    <a class="post-title-link" href="/2018/08/14/43/" itemprop="url">常见“树”概念解析(1)</a></h1>
    h1
    {u'class': [u'post-title'], u'itemprop': u'name headline'}
    [u'post-title']

    2.2.2 NavigableString对象

    用来表示包含在tag中的文字。注意!如果tag中包含子tag,navigableString对象会是None!

    2.2.3 Comment对象

    用来查找HTML里的注释标签。是一个特殊的NavigableString,所以也有其性质。

    2.3 导航树(Navigating Trees)

    2.3.1 子节点们

    对tag级别调用childen属性可得到该tag的所有子节点:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://blog.orisonchan.cc")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    for child in bsObj.find(name='h1', attrs={'class': {'post-title'}}).children:
        print(child)

    结果

    <a class="post-title-link" href="/2018/08/14/43/" itemprop="url">常见“树”概念解析(1)</a>

    2.3.2 兄弟节点(们)

    next_siblings属性和previous_siblings属性可以查询兄弟节点们。

    next_sibling和previous_sibling可以查下一个/上一个兄弟。

    需要注意的是,很可能直接相邻的上一个下一个兄弟节点并不是Tag而是一个换行符啊标点符号啊等NavigableString对象(字符串节点)。

    2.3.3 父节点(们)

    parent属性得到某元素父节点。

    parents属性递归得到所有的父节点。

    2.4 过滤器

    2.4.1 字符串

    即上文提到bsObj.find_all("a")和bsObj("a")。

    2.4.2 标签列表

    形如bsObj.find_all(["a", "p"])则会去寻找a标签和p标签。

    2.4.3 True

    True可以匹配任何职,但是不会返回字符串节点

    2.4.4 正则表达式

    引入Python自带的re(regular expressions)

    示例:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    import re
    html = urlopen("http://blog.orisonchan.cc/2018/08/14/43")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    print bsObj.find_all(name='img', attrs={'src': re.compile("[a-z]*.png")})[1]

    结果

    <img alt="red-black-tree" src="/uploads/2018/08/red-black-tree.png"/>

    2.4.5 自定义方法作为参数

    这个不知道该怎么表述,有兴趣的可以去官方文档看一下,这里直接来一个demo:

    from urllib import urlopen
    from bs4 import BeautifulSoup
    import re
    html = urlopen("http://blog.orisonchan.cc/2018/08/14/43")
    bsObj = BeautifulSoup(html.read(), 'html.parser')
    
    
    def png_image(tag):
        return tag.name == "img" and re.compile("[a-z]*tree.png").search(tag.attrs["src"])
    
    
    for img in bsObj.find_all(png_image):
        print(img)

    结果返回了该篇文章4个img中的3个:

    <img alt="binary-search-tree" src="/uploads/2018/08/binary-search-tree.png"/>
    <img alt="red-black-tree" src="/uploads/2018/08/red-black-tree.png"/>
    <img alt="sentinel-in-list" src="/uploads/2018/08/b-tree.png"/>

    下载网 » Python爬虫学习之BeautifulSoup4的简单用法

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元