首页 > 其他分享 >实验八. urllib模块、requests模块+BeautifulSoup模块使用、Feapder框架

实验八. urllib模块、requests模块+BeautifulSoup模块使用、Feapder框架

时间:2023-11-14 23:34:12浏览次数:34  
标签:name text Feapder BeautifulSoup content headers html 模块

一、实验目标:

熟悉模块的的用法,练习编写爬虫

二、实验要求:

编写代码,完成功能

三、实验内容:

(1)使用urllib模块或request模块读取网页内容,并利用BeautifulSoup模块进行内容解析,编写爬虫从http://www.cae.cn/cae/html/main/col48/column_48_1.html爬取中国工程院院士信息

  • 模块导入:
import requests
from bs4 import BeautifulSoup
  • 伪造请求头:
image.png
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
}
  • 爬取信息:
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
}
response1 = requests.get("http://www.cae.cn/cae/html/main/col48/column_48_1.html",headers=headers)
content = response1.text
soup = BeautifulSoup(content, "html.parser")
names_lists = soup.find_all("li", attrs={"class": "name_list"})
for name in names_lists:
    li = BeautifulSoup(str(name), "html.parser")
    Name = li.find_all('a')
    link = Name[0].get('href')
    Link = "http://www.cae.cn"+link
    Content = requests.get(Link,headers=headers).text
    Soup = BeautifulSoup(Content,"html.parser")
    Intro = Soup.find_all("div",attrs={"class":"intro"})
    intro = BeautifulSoup(str(Intro[0]),"html.parser")
    text = intro.find_all("p")
    Text=''
    for i in text:
        Text=Text+i.text
    with open(r"C:\Users\86135\Desktop\院士名单.txt", 'a', encoding='utf-8') as f:#写入文件
        f.write(Name[0].string+'\n')
        f.write(Text+'\n')
        f.write('\n')
  • 爬取结果:

image.png

(2)使用urllib模块或request模块读取网页内容,并利用BeautifulSoup模块进行内容解析,编写爬虫从https://www.biqukan.com/2_2671爬取小说《余罪》的内容。要求最终爬取的内容从第一章开始,且不存在大量空格等非必要字符。

由于小说首页不是从第一章开始,我们需要确定第一章的起始位置和最后一章的终止位置

image.png

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
}
content = requests.get("https://www.biqukan8.cc/2_2671",headers=headers).text
soup = BeautifulSoup(content,"html.parser")
titles = soup.find_all('a')
num = 0
global start , end
for title in titles:
    num = num + 1
    if title.string == '第1章 好事上门':
        start = num
    if title.string == "都市之战神之王陈锋林雨欣":
        end = num

然后处理html中的a标签中的href元素得到每一章跳转的url

for i in range(start-1,end-1):
    link = BeautifulSoup(str(titles[i]),"html.parser")
    Li = link.find("a")
    Link = "https://www.biqukan8.cc/"+Li["href"]

然后爬取每一个Link中的特征为div,class为showtxtidcontent的小说正文,并将标题和正文写入文件

for i in range(start-1,end-1):
    link = BeautifulSoup(str(titles[i]),"html.parser")
    Li = link.find("a")
    Link = "https://www.biqukan8.cc/"+Li["href"]
    content = requests.get(Link,headers=headers).text
    Soup = BeautifulSoup(content,"html.parser")
    novel_content = Soup.find('div', {'class': 'showtxt', 'id': 'content'})
    novel_text = novel_content.get_text(separator="\n")
    with open(r"C:\Users\86135\Desktop\余罪.txt", 'a', encoding='utf-8') as f:
        f.write(titles[i].string+'\n')
        f.write(novel_text+'\n')
        f.write('\n')

最后添加一个可以实时显示进度的功能,完整代码如下:

import requests
import sys
from bs4 import BeautifulSoup
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
}
content = requests.get("https://www.biqukan8.cc/2_2671",headers=headers).text
soup = BeautifulSoup(content,"html.parser")
titles = soup.find_all('a')
num = 0
global start , end
for title in titles:
    num = num + 1
    if title.string == '第1章 好事上门':
        start = num
    if title.string == "都市之战神之王陈锋林雨欣":
        end = num
for i in range(start-1,end-1):
    link = BeautifulSoup(str(titles[i]),"html.parser")
    Li = link.find("a")
    Link = "https://www.biqukan8.cc/"+Li["href"]
    content = requests.get(Link,headers=headers).text
    Soup = BeautifulSoup(content,"html.parser")
    novel_content = Soup.find('div', {'class': 'showtxt', 'id': 'content'})
    novel_text = novel_content.get_text(separator="\n")
    with open(r"C:\Users\86135\Desktop\余罪.txt", 'a', encoding='utf-8') as f:
        f.write(titles[i].string+'\n')
        f.write(novel_text+'\n')
        f.write('\n')
    if (i + 1) % 10 == 0:
        # 将下载进度输出到控制台,实时变动
        sys.stdout.write("  已下载:%.3f%%" % float((i + 1) * 100 / (end-start+2)) + '\r')
        # 刷新缓存区
        sys.stdout.flush()
print('下载完成')
print("————————END————————")
  • 爬取结果:

image.png

(3)学习使用Feapder框架,编写爬虫,爬取中国工程院院士信息。

import feapder

class TophubSpider(feapder.AirSpider):
    def start_requests(self):
        yield feapder.Request("http://www.cae.cn/cae/html/main/col48/column_48_1.html")

    def parse(self, request, response):
        # 提取网站title
        print(response.xpath("//title/text()").extract_first())
        # 提取网站描述
        print(response.xpath("//meta[@name='description']/@content").extract_first())
        print("网站地址: ", response.url)

        # 提取所有class为name_list的li元素下的a元素的href和文本内容
        items = response.xpath("//li[@class='name_list']//a")
        for item in items:
            href = item.xpath("@href").extract_first()
            person_name = item.xpath("string(.)").extract_first()
            print("Found href:", href)

            # Follow the link and parse the information from the 'intro' div
            yield feapder.Request(url=href, callback=self.parse_intro, meta={'person_name': person_name})

    def parse_intro(self, request, response):
        # Extract information from the 'intro' div
        intro_text = response.xpath("//div[@class='intro']//p/text()").extract()

        # Concatenate the text and remove extra spaces
        formatted_text = " ".join(map(str.strip, intro_text))

        # Extract person_name from meta
        person_name = request.meta['person_name']

        # Write person_name and information to the file
        with open(r"C:\Users\86135\Desktop\院士信息.txt", "a", encoding="utf-8") as file:
            file.write(person_name + "\n")
            file.write(formatted_text + "\n")

        print(f"Information for {person_name} has been saved to 工程院士信息.txt")

if __name__ == "__main__":
    TophubSpider().start()

四、实验总结:

本次实验对python的BeautifulSoup+request模块的使用有了更深刻的理解,对Feapder框架的使用有了进一步的了解。

标签:name,text,Feapder,BeautifulSoup,content,headers,html,模块
From: https://www.cnblogs.com/Smera1d0/p/17832857.html

相关文章

  • 国标GB28181安防视频LiteCVR平台GIS电子地图模块开发介绍
    电子地图应用主要以GIS地理信息系统为核心,在联网监控工程视频监控业务管理中具有重要意义,能发挥GIS系统“一张图”可视化集成展示和空间决策分析方面的优势。视频监控平台LiteCVR可拓展性强、视频能力灵活、部署轻快,可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等,以及......
  • 如何根据不同仪器选择适合的电源模块?
    BOSHIDA如何根据不同仪器选择适合的电源模块?在实验室、工业生产等场合中,电源模块是必不可少的设备之一。电源模块的作用是将输入电能转换成所需要的电压和电流,为各种仪器设备提供恰当的电源。不同的仪器设备对电源的要求不同,因此在选择电源模块时需要根据具体的情况进行选择。下......
  • 如何平衡DC电源模块的体积和功率?
    如何平衡DC电源模块的体积和功率?BOSHIDADC电源模块是一种常见的电源设备,它通常用于将交流电转换为直流电以供各种电子设备使用。电源模块的体积和功率是电源模块设计中需要考虑和平衡的两个关键因素。在本文中,我们将探讨DC电源模块的体积和功率之间的关系,并讨论如何找到它们之间的......
  • 关于 DC电源模块的体积与功率达到平衡的关系
    关于BOSHIDADC电源模块的体积与功率达到平衡的关系DC电源模块是一种将交流电转换为直流电的装置。它是许多电子设备中非常重要的部分,尤其是电子产品的便携性和用电时间方面,一直是DC电源模块必须考虑的因素。因此,电源模块的体积和功率之间的平衡非常重要,可以影响到电源模块的性能和......
  • DC电源模块的价格因素是什么?如何进行成本优化?
    BOSHIDADC电源模块的价格因素是什么?如何进行成本优化?DC电源模块是一种用于直流电路中的电源转换器,主要用于将输入电源的电压、电流和频率转换为适合设备的直流电源。随着电子设备的广泛应用,DC电源模块的需求也日益增加。而DC电源模块的价格因素主要有以下几个方面:1.元器件成本:DC电......
  • 如何解决DC电源模块的电源噪声问题
    BOSHIDA如何解决DC电源模块的电源噪声问题在电子设备的设计和制作过程中,电源噪声是一个非常重要的考虑因素。DC电源模块的电源噪声问题是电子设备中普遍存在的问题之一。它不仅会影响设备的性能,还会对设备的寿命和稳定性产生负面影响。因此,解决DC电源模块的电源噪声问题非常重要。......
  • DC电源模块隔离电路的影响
    BOSHIDADC电源模块隔离电路的影响DC电源模块隔离电路是电子设备中常用的一种电路。它的作用是在设备中两个电路之间建立一定的隔离,以保证两个电路之间不会传递电流或信号。这种隔离电路的影响可以从以下几个方面来分析。首先,隔离电路可以提高安全性。隔离电路可以将设备中的不同电......
  • 制造业工厂生产管理MES系统中的设备管理模块
    制造业工厂万界星空科技生产管理MES系统中的设备管理模块介绍:随时工厂数字化建设的大力推进,设备管理的效率得到了很大的提升,特别是作为机加工企业,设备是整个企业非常重要的核心资产。1、MES设备管理任务模型制造企业总是期望设备能够在计划生产的时间段内处于良好的运行状态,而......
  • 手撕Vuex-安装模块数据
    前言根据上一篇,【手写Vuex】-提取模块信息,我们已经可以获取到模块的信息了,将模块信息变成了我们想要的数据结构,接下来我们就要根据模块的信息,来安装模块的数据。在上一篇当中我们定义了一个ModuleCollection类,这个类的作用就是将模块的信息转换成我们想要的数据结构。接下来......
  • MT8788/MTK8788安卓核心板介绍_4G全网通安卓智能模块
    MT8788核心板是一款功能强大的4G全网通安卓智能模块。它采用联发科AIOT芯片平台,具有超高性能和低功耗的特点。该核心板搭载了12nm制程四个Cortex-A73+四个Coretex-A53处理器,最高主频可达2.0GHZ。内存方面,板载内存为4GB+64GB,同时也支持2GB+16GB和3GB+32GB的配置。图形方面,MT8788......