爬虫 | 【实践】Best Computer Science Scientists数据爬取

2023-10-16 22:52

本文主要是介绍爬虫 | 【实践】Best Computer Science Scientists数据爬取,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 📚数据需求
  • 📚数据爬取
    • 🐇排行榜页数据爬取
    • 🐇获取详情页
    • 🐇目标信息提取
  • 📚完整代码与结果

📚数据需求

  • 姓名,国家,学校
    在这里插入图片描述

  • 最有名研究领域
    在这里插入图片描述

  • 目前研究领域
    在这里插入图片描述

  • 共同作者
    在这里插入图片描述

  • D-index、引用、出版物、世界排名、国家排名
    在这里插入图片描述

📚数据爬取

🐇排行榜页数据爬取

# 以for循环实现翻页,总共20页
for page in range(1, 21):# 前缀f表示该字符串是一个格式化字符串,允许我们在字符串中嵌入变量或表达式的值。# 这里嵌入变量page,实现翻页后的url对应url = f"https://research.com/scientists-rankings/computer-science?page={page}"# 获得响应response = requests.get(url=url, headers=headers)# 智能解码response.encoding = response.apparent_encoding# 使用etree.HTML函数将HTML文本转换为可进行XPath操作的树结构对象tree。tree = etree.HTML(response.text)# 提取id为"rankingItems"元素下的所有div子元素的列表div_list = tree.xpath('//*[@id="rankingItems"]/div')
  • 定位到id="rankingItems
    在这里插入图片描述
  • 每一个div是每一条排行记录
    在这里插入图片描述

🐇获取详情页

# 循环取出div_list内容for i in div_list:# 获取当前科学家的详情页地址href = 'https://research.com' + i.xpath('.//div//h4/a/@href')[0]print(href)# 调用等待时间函数,防止宕机random_wait()# 获得详情页响应response_detail = requests.get(url=href, headers=headers)# 智能解码response.encoding = response.apparent_encoding# 使用etree.HTML函数将HTML文本转换为可进行XPath操作的树结构对象tree。tree_detail = etree.HTML(response_detail.text)
  • .//div//h4/a/@href获取对应科学家详情页相关信息,通过href = 'https://research.com' + i.xpath('.//div//h4/a/@href')[0]得到详情页url
    在这里插入图片描述
  • 对应详情页url如下所示
    在这里插入图片描述

🐇目标信息提取

  • 姓名
    # 名字,依次找到htm → body → 第1个div → 第2个div → 第1个div → div → h1元素,匹配文本内容
    # .strip()用于去除文本内容两端的空白字符,包括空格、制表符和换行符。
    name = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/h1/text()')[0].strip()
    
    在这里插入图片描述

  • 国家

    country = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/div/p/a[2]/text()')[0].strip()
    

    在这里插入图片描述


  • 学校

    university = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/div/p/a[1]/text()')[0].strip()
    

    在这里插入图片描述


  • 最有名研究领域

    try:research_field1 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[0].strip()research_field2 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[1].strip()research_field3 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[2].strip()
    except:# 异常处理,有些详情页无对应数据research_field1="无研究领域"research_field2="无研究领域"research_field3 ="无研究领域"
    

    在这里插入图片描述


  • 目前研究领域

    try:
    # 目前研究领域# 将匹配正则表达式pattern的内容替换为空字符串。删除括号及其内部的内容。now_research_field1 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[0].strip())now_research_field2 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[1].strip())now_research_field3 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[2].strip())
    except:now_research_field1="无研究领域"now_research_field2="无研究领域"now_research_field3 ="无研究领域"
    

    在这里插入图片描述


  • 共同作者
    # 共同作者,定位后源码里的第一个div不要
    Frequent_CoAuthors = tree_detail.xpath('/html/body/div[1]/div[4]/div[2]/div/div')[1:]
    # 共同关系的人
    for i in Frequent_CoAuthors:common_name = i.xpath('.//h4/a/text()')[0].strip().replace('\n', '')friend_list.append(common_name)
    # 将共同关系的人拼成一个字符串
    result = ', '.join(friend_list)
    
    • tree_detail.xpath('/html/body/div[1]/div[4]/div[2]/div/div')[1:]——定位到列表框
      在这里插入图片描述
    • i.xpath('.//h4/a/text()')[0].strip().replace('\n', '')——定位到每个人
      在这里插入图片描述

  • 各项数据、排名等

    # 各项数据,排名等等,[-1:]返回匹配结果列表中的最后一个元素
    data_list = tree_detail.xpath('//*[@id="tab-1"]/div/div')[-1:]
    for a in data_list:# D-indexD_index = a.xpath('.//span[2]//text()')[-1].replace(' ', '').replace('\n', '')# 引用Citations = a.xpath('.//span[3]//text()')[-1].replace(' ', '').replace('\n', '').replace(',', '')# 出版物publication = a.xpath('.//span[4]//text()')[-1].replace(' ', '').replace('\n', '').replace(',', '')# 世界排名world_rank = a.xpath('.//span[5]//text()')[-1].replace(' ', '').replace('\n', '')# 国家排名national_rank = a.xpath('.//span[6]//text()')[-1].replace(' ', '').replace('\n', '')
    
    • //*[@id="tab-1"]/div/div——定位到数据表格
      在这里插入图片描述

    • a.xpath('.//span[2]//text()')[-1]——D-index 在这里插入图片描述

    • a.xpath('.//span[3]//text()')[-1]——引用
      在这里插入图片描述

    • a.xpath('.//span[4]//text()')[-1]——出版物
      在这里插入图片描述

    • 世界排名和国家排名

       # 世界排名world_rank = a.xpath('.//span[5]//text()')[-1].replace(' ', '').replace('\n', '')# 国家排名national_rank = a.xpath('.//span[6]//text()')[-1].replace(' ', '').replace('\n', '')
      

      在这里插入图片描述

      在这里插入图片描述

📚完整代码与结果

import requests
from lxml import etree
import openpyxl
import re
import random
import time# 随机等待时间的函数
# 避免以高频率向服务器发送请求造成宕机
def random_wait():# 生成一个随机的等待时间,范围为1到5秒wait_time = random.uniform(1, 5)time.sleep(wait_time)# openpyxl用于操作Excel文件。它允许我们读取、写入和修改Excel文件中的数据。
# 创建一个新的Excel工作簿对象
workbook = openpyxl.Workbook()
# 返回工作簿中的活动工作表对象,表明之后的代码对这个工作表进行操作
worksheet = workbook.active
# 添加标题
worksheet.append(['姓名', '国家', '学校', '最有名研究领域1', '最有名研究领域2', '最有名研究领域3', '目前研究领域1', '目前研究领域2','目前研究领域3', '共同作者', 'D-index', '引用', '出版物', '世界排名', '国家排名'])# 伪装请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0'
}# 以for循环实现翻页,总共20页
for page in range(1, 21):# 前缀f表示该字符串是一个格式化字符串,允许我们在字符串中嵌入变量或表达式的值。# 这里嵌入变量page,实现翻页后的url对应url = f"https://research.com/scientists-rankings/computer-science?page={page}"# 获得响应response = requests.get(url=url, headers=headers)# 智能解码response.encoding = response.apparent_encoding# 使用etree.HTML函数将HTML文本转换为可进行XPath操作的树结构对象tree。tree = etree.HTML(response.text)# 提取id为"rankingItems"元素下的所有div子元素的列表div_list = tree.xpath('//*[@id="rankingItems"]/div')# 循环取出div_list内容for i in div_list:# 获取当前科学家的详情页地址href = 'https://research.com' + i.xpath('.//div//h4/a/@href')[0]print(href)# 调用等待时间函数,防止宕机random_wait()# 获得详情页响应response_detail = requests.get(url=href, headers=headers)# 智能解码response.encoding = response.apparent_encoding# 使用etree.HTML函数将HTML文本转换为可进行XPath操作的树结构对象tree。tree_detail = etree.HTML(response_detail.text)# 用于删除括号及其内部的内容,主要是对后边最近研究领域后续括号内的百分比进行删除pattern = r'\([^()]*\)'# 存取共同作者的列表friend_list = []try:# 名字,依次找到htm → body → 第1个div → 第2个div → 第1个div → div → h1元素,匹配文本内容# .strip()用于去除文本内容两端的空白字符,包括空格、制表符和换行符。name = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/h1/text()')[0].strip()# 国家country = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/div/p/a[2]/text()')[0].strip()# 学校university = tree_detail.xpath('/html/body/div[1]/div[2]/div[1]/div/div/p/a[1]/text()')[0].strip()# 最有名研究领域try:research_field1 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[0].strip()research_field2 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[1].strip()research_field3 = tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[1]/li/text()')[2].strip()except:# 异常处理,有些详情页无对应数据research_field1="无研究领域"research_field2="无研究领域"research_field3 ="无研究领域"try:# 目前研究领域# 将匹配正则表达式pattern的内容替换为空字符串。删除括号及其内部的内容。now_research_field1 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[0].strip())now_research_field2 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[1].strip())now_research_field3 = re.sub(pattern, '', tree_detail.xpath('//*[@class="tab bg-white shadow"]//ul[4]/li/text()')[2].strip())except:now_research_field1="无研究领域"now_research_field2="无研究领域"now_research_field3 ="无研究领域"# 共同作者,定位后源码里的第一个div不要Frequent_CoAuthors = tree_detail.xpath('/html/body/div[1]/div[4]/div[2]/div/div')[1:]# 共同关系的人for i in Frequent_CoAuthors:common_name = i.xpath('.//h4/a/text()')[0].strip().replace('\n', '')friend_list.append(common_name)# 将共同关系的人拼成一个字符串result = ', '.join(friend_list)# 各项数据,排名等等,[-1:]返回匹配结果列表中的最后一个元素data_list = tree_detail.xpath('//*[@id="tab-1"]/div/div')[-1:]for a in data_list:# D-indexD_index = a.xpath('.//span[2]//text()')[-1].replace(' ', '').replace('\n', '')# 引用Citations = a.xpath('.//span[3]//text()')[-1].replace(' ', '').replace('\n', '').replace(',', '')# 出版物publication = a.xpath('.//span[4]//text()')[-1].replace(' ', '').replace('\n', '').replace(',', '')# 世界排名world_rank = a.xpath('.//span[5]//text()')[-1].replace(' ', '').replace('\n', '')# 国家排名national_rank = a.xpath('.//span[6]//text()')[-1].replace(' ', '').replace('\n', '')print(name, country, university, research_field1, research_field2, research_field3, now_research_field1,now_research_field2, now_research_field3, result, D_index, Citations, publication, world_rank, national_rank)# 清空列表friend_list.clear()# 将数据添加到excel表格内worksheet.append([name, country, university, research_field1, research_field2, research_field3, now_research_field1,now_research_field2, now_research_field3, result, D_index, Citations, publication, world_rank, national_rank])# 保存workbook.save('world_data.csv')except:worksheet.append(['无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据', '无数据'])# 保存workbook.save('world_data.csv')

在这里插入图片描述在这里插入图片描述

这篇关于爬虫 | 【实践】Best Computer Science Scientists数据爬取的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/221299

相关文章

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

MyBatisPlus如何优化千万级数据的CRUD

《MyBatisPlus如何优化千万级数据的CRUD》最近负责的一个项目,数据库表量级破千万,每次执行CRUD都像走钢丝,稍有不慎就引起数据库报警,本文就结合这个项目的实战经验,聊聊MyBatisPl... 目录背景一、MyBATis Plus 简介二、千万级数据的挑战三、优化 CRUD 的关键策略1. 查

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

mysql中的数据目录用法及说明

《mysql中的数据目录用法及说明》:本文主要介绍mysql中的数据目录用法及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、版本3、数据目录4、总结1、背景安装mysql之后,在安装目录下会有一个data目录,我们创建的数据库、创建的表、插入的

MySQL 中 ROW_NUMBER() 函数最佳实践

《MySQL中ROW_NUMBER()函数最佳实践》MySQL中ROW_NUMBER()函数,作为窗口函数为每行分配唯一连续序号,区别于RANK()和DENSE_RANK(),特别适合分页、去重... 目录mysql 中 ROW_NUMBER() 函数详解一、基础语法二、核心特点三、典型应用场景1. 数据分