• python3


    • 导入需要的模块
    • 需要安装BeautifulSoup
    
    from urllib.request import urlopen, HTTPError, URLError
    from bs4 import BeautifulSoup
    import re
    
    
    
    • 要抓取的内容里面的链接如图

    • 打开网页审查查看标签如图:

    • 可以看出内容属于标签dd 以及 dd的属性是 class="desc"则:

    • 如果有异常则打印HTTPError, URLError异常内容

      • 首先查找标签bsObj.find('dd', {'class':'desc'})
      • 再查找dd标签下的子标签a,标签a的属性href用正则表达式匹配筛选,因为其下面的链接是以view或者subview开头的
      • 判断如果href属性在标签a中则打印链接.最后完成打印.
    
    try:
        html = urlopen('http://baike.baidu.com/link?url=FfHqPzChV9Iz7Kz0d2Mke-1njFShGt8fsFJ5mmyh-t48rnjLMbQNyeBFfmUz3oOCVvRSt0GHJ-nXDqbq9bgrZldbYDPUiQBNckuTBiGt-2Uss1aIWbhj7ELhOfrF3XoFeK2I0mSJ1ERslKeS0wUXtK')
    except (HTTPError, URLError) as e:
        print(e)
    bsObj = BeautifulSoup(html, 'lxml')
    for link in bsObj.find('dd', {'class':'desc'}).find_all('a', href=re.compile('^((/view/)*(/subview/)*)((?!:).)*$')):
        if 'href' in link.attrs:
            print(link.attrs['href'])
        else:
            print('not in it')
    
    
    
    • 打印内容如下:

    • 高级一点定义一个方法,只需要传入参数url即可

    • 这次打印时为每个抓取的链接添加上以及内容

    
    def getLinks(url):
        try:
            html = urlopen(url)
        except (HTTPError, URLError) as e:
            print(e)
        bsObj = BeautifulSoup(html, 'lxml')
        return bsObj.find('dd', {'class': 'desc'}).find_all('a', href=re.compile('^((/view/)*(/subview/)*)((?!:).)*$'))
    
    linkTest = getLinks('http://baike.baidu.com/link?url=FfHqPzChV9Iz7Kz0d2Mke-1njFShGt8fsFJ5mmyh-t48rnjLMbQNyeBFfmUz3oOCVvRSt0GHJ-nXDqbq9bgrZldbYDPUiQBNckuTBiGt-2Uss1aIWbhj7ELhOfrF3XoFeK2I0mSJ1ERslKeS0wUXtK')
    for link in linkTest:
        if 'href' in link.attrs:
            print('http://baike.baidu.com' + link.attrs['href'] + ' -- ' + link.get_text())
        else:
            print('not in it')
    
    
    
    • 打印结果如下:

    练习抓取百度百科中人物 以及 人物 的老婆 或者 老公 就以 凯文·贝肯为例子

    • 要抓取的界面链接如图:

    • 打开网页检查查看代码如图:

    • 由于div标签的属性class="viewport"id="slider_relations是唯一的则先找到这个目标标签div -- bsObj.find_all('div', {'class': 'viewport','id':'slider_relations'})

    • 紧接着在目标标签div下查找标签a -- find_all('a'),找到后获取href属性children['href']并返回.

    • 其中不太了解的是 bsObj.find_all('div', {'class': 'viewport','id':'slider_relations'})[0].find_all('a')[0]两个中括号[0]取值是什么原理? 个人理解是 list -- 角标提取元素

    • 得到凯文·贝肯他老婆的链接后直接带入方法getLinks(url)得到凯文·贝肯,顺便在方法中打印出来各自链接对应的名字print(children.get_text())

    
    # 百度百科夫妻
    def getLinks(url):
        try:
            html = urlopen(url)
        except (HTTPError, URLError) as e:
            print(e)
        bsObj = BeautifulSoup(html, 'lxml')
        children = bsObj.find_all('div', {'class': 'viewport','id':'slider_relations'})[0].find_all('a')[0]
        print(children.get_text())
        return children['href']
    
    newLink = getLinks('http://baike.baidu.com/link?url=FfHqPzChV9Iz7Kz0d2Mke-1njFShGt8fsFJ5mmyh-t48rnjLMbQNyeBFfmUz3oOCVvRSt0GHJ-nXDqbq9bgrZldbYDPUiQBNckuTBiGt-2Uss1aIWbhj7ELhOfrF3XoFeK2I0mSJ1ERslKeS0wUXtK')
    print(newLink)
    newLinkTwo = getLinks(newLink)
    print(newLinkTwo)
    
    
    • 打印结果如下:
  • 相关阅读:
    AcRxClass::addX
    string.format("%s",name)
    strcmp 与 _tcscmp
    acedinitget
    判断实体的类型 相关操作
    accmcolor
    CAD类型转换
    图的存储结构及遍历
    并查集(Union/Find)
    设计模式--缺醒适配器模式
  • 原文地址:https://www.cnblogs.com/adampei-bobo/p/6397887.html
Copyright © 2020-2023  润新知