美文网首页
初级爬虫使用指北(7)--完整代码

初级爬虫使用指北(7)--完整代码

作者: ArthurN | 来源:发表于2018-08-12 22:10 被阅读0次

    目录

    1. 完整代码
    2. 附加题

    1. 完整代码

    prepare_fellow_list.py

    ACM的fellow列表
    import requests
    import pickle
    
    # ----------- 准备阶段
    # 伪装
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Connection': 'keep-alive',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    }
    
    # 获取网页源代码
    def visitHtml(url):
        '''访问网页'''
        return requests.get(url, headers=headers)
    
    # 清理网页文本数据
    def cleanStr(text):
        ''' 清理网页字符串里的无用字符'''
        # 清理 空格
        # 'Masinter,\xa0Larry\xa0M' -> 'Masinter, Larry M'
        # \xa0 是 html 里的空格  
        text.replace('\xa0', ' ')
    
        text.replace('\t', '')  # 清理 回车
        text.replace('\n', '')  # 清理 退格
    
        return text
    
    
    # ----------- 开始爬虫
    # 目标网址
    url = 'https://awards.acm.org/fellows/award-winners'
    
    # 获取对应网页源代码
    html = visitHtml(url)
    
    # 解析
    soup = BeautifulSoup(html.content, 'lxml')
    
    # 找到指定的标签
    t_table = soup.find(
        'table', attrs={'summary': 'Awards Winners List'})
    
    # 使用一个列表放置数据
    fellowList = []
    
    # 对于每一个找到的‘tr’标签,循环处理
    for tr in t_table.tbody.find_all('tr', attrs={'role': 'row'}):
    
        # 找到‘tr’中的‘td’标签
        tdList = tr.find_all('td')
    
        # 第一个‘td’标签是 姓名
        name = tdList[0].string
        cleanStr(name)
    
        # 第三个‘td’标签是 年份
        year = tdList[2].string
        cleanStr(year)
    
        # 第四个‘td’标签是 来源
        nation = tdList[3].string
        cleanStr(nation)
    
        # 第五个‘td’标签是 对应的Digital Library 的档案链接
        dlLink = tdList[4].a['href']
    
        # 把这些标签的内容放置于列表中
        fellowList.append([name, year, nation, dlLink])
    
    # ----------- 使用pickle存储数据
    # 存入当前文件夹下的data文件夹
    dataDict = '/data/'
    
    # 存储网页源代码,方便日后重复使用
    html_file_name = 'fellow_page.pickle'
    with open(dataDict + html_file_name, 'wb') as f:
        pickle.dump(html, f)
    
    # 存储 专家列表,下一步解析需要使用
    fellows_file_name = 'fellow_list.pickle'
    with open(dataDict + fellows_file_name, 'wb') as f:
        pickle.dump(fellowList, f)
    
    
    # ----------- 显示一些基础信息
    print('How many fellow I obtain?')
    print(len(fellowList))
    
    

    crawl_multiple.py

    对应的DL档案信息
    import pickle
    import csv
    import requests
    from bs4 import BeautifulSoup
    
    # ----------- 准备阶段
    # 伪装
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Connection': 'keep-alive',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    }
    
    # 填入对应文件路径
    dataDict = '/data/'
    fellows_file_name = 'fellow_list.pickle'
    with open(dataDict + fellows_file_name, 'rb') as f:
        fellowList = pickle.load(f)
    
    def visitHtml(url):
        '''访问网页'''
        return requests.get(url, headers=headers)
    
    # 收集 affilication history 的信息
    def collectAffiliation(soup):
        # 根据table标签特有的属性找到 想要的它
        tableList_aff = soup.find_all(
            'table',
            attrs={'align': 'center', 'border': '0',
                   'cellpadding': '0', 'cellspacing': '0'})
    
        # 确认找到的内容是否正确
        table = None
        if len(tableList_aff) == 1:  # 只找到一个,那么就是它
            table = tableList_aff[0]
    
        else:  # 如果找到超过一个,那么查看该内容是否含有 'Affiliation' 字样
            for tb in tableList_aff:
                if 'Affiliation' in str(tb.text):
                    table = tb
                    break
    
        # 找出这个table标签下的所有 a标签
        affilication = []
        for a in table.div.find_all('a'):
            affilication.append(a.string)  # a.string 即是 Carnegie Mellon University
    
        return affilication
    
    # 收集 publication 相关的信息
    def collectPublication(soup):
    
        # 根据table标签特有的属性找到 想要的它
        tableList_pub = soup.find_all(
            'table',
            attrs={'width': '90%', 'style': 'margin-top: 1px; margin-bottom: 10px',
                   'border': '0', 'align': 'left'})
    
        # 确认找到的内容是否正确
        table = None
        if len(tableList_aff) == 1:  # 只找到一个,那么就是它
            table = tableList_aff[0]
    
        else:  # 如果找到超过一个,那么查看该内容是否含有 'Affiliation' 字样
            for tb in tableList_aff:
                if 'Average citations per article' in str(tb.text):
                    table = tb
                    break
    
        # 找出这个table标签下的所有 tr标签 内的所有 td标签
        publication = []
        for tr in table.find_all('tr'):
            tdList = tr.find_all('td')
    
            if len(tdList) != 2:  # 如果该 tr标签内没有 td标签
                continue  # 跳过以下内容,直接进入下一次循环
    
            item = tdList[0].string  # e.g., Average citations per article
            value = tdList[1].string  # e.g., 12.95
    
            publication.append([item, value])  # 放入一个列表中
    
        return publication
    
    # ----------- 开始爬虫
    fellowInfoList = []
    
    for fellow in fellowList:
    
        # 获得网站解析结果
        html = visitHtml(fellow[3])  # 第四项即是 digital library 的网址
        soup = BeautifulSoup(html.content, 'lxml')
    
        # 填充基础信息 name, year, nation
        expertInfo = [fellow[0], fellow[1], fellow[2]]
    
        # 收集 affiliation history
        aff = collectAffiliation(soup)
        expertInfo.append(','.join(aff))
    
        # 收集 publication 信息
        pub = collectPublication(soup)
        expertInfo.extend([v[1] for v in pub])
    
        fellowInfoList.append(expertInfo)
        break  # 该命令 使得循环提前结束,不再继续其他循环,这里用于让循环的内容只运行一次
    
    # ----------- 使用csv存储数据
    # 这是表格的标题栏
    title = ['name', 'year', 'nation', 'affilication', 'Average citations per article', 'Citation Count',
             'Publication count', 'Publication years', 'Available for download', 'Average downloads per article',
             'Downloads (cumulative)', 'Downloads (12 Months)', 'Downloads (6 Weeks)']
    
    csv_file_name = 'fellow_info.csv'  # 文件名称
    
    with open(dataDict + csv_file_name, 'a+', encoding='utf-8', newline='') as f:
        writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
    
        writer.writerow(title)  # 写入标题栏
    
        for row in fellowInfoList:  # 循环写入每一行信息
            writer.writerow(row)
    
    # ----------- 显示一些基础信息
    print('How many experts do I obtain?')
    print(len(fellowInfoList))
    print()
    print('?? too little !')
    

    2. 附加题

    我相信有了这个教程,大多数基础的数据收集任务应该可以完成了。但是“爬虫”仍然需要很多Python基础知识。当你完成基础知识的学习后,再来看这些教程也不迟。

    相关文章

      网友评论

          本文标题:初级爬虫使用指北(7)--完整代码

          本文链接:https://www.haomeiwen.com/subject/oogbuftx.html