AI网络爬虫:批量爬取电视猫上面的《庆余年》分集剧情

电视猫上面有《庆余年》分集剧情,如何批量爬取下来呢?

先找到每集的链接地址,都在这个class="epipage clear"的div标签里面的li标签下面的a标签里面:

<a href="/drama/Yy0wHDA=/episode">1</a>

这个链接是相对地址,前面加上https://www.tvmao.com,才是完整的URL地址;

每集的标题在p标签里面:

<p class="epi_t">

第7集:范闲赴诗会作绝句惊艳京城

</p>

在kimi中输入提示词:

你是一个Python编程专家,要完成以下任务的Python脚本的编写:

打开网页:https://www.tvmao.com/drama/Yy0wHDA=/episode

在源代码中定位class="epipage clear"的div标签;

提取div标签里面所有a标签的href值,前面加上"https://www.tvmao.com",构成网页下载URL;

解析URL,定位class="epi_t"的p标签,提取其文本内容,作为txt文档文件名;提取class="clear epi_c"的article标签里面的文本内容,保存为txt文档到D盘下的qyn文件夹;

注意:

每下载一个网页,随机暂停1-10秒;

网页文件名要进行处理,去除不符合window系统文件命名规范的特殊字符,处理文件名时要确保文件名中不包含任何特殊字符或不可见字符,可以通过使用strip()方法来去除字符串两端的空白字符,包括换行符和空格;

每一步都要输出信息到屏幕

要有应对反爬虫的措施,设置请求头;

生成的源代码如下:

import requests

from bs4 import BeautifulSoup

import random

import time

import os

目标网页URL

url = 'https://www.tvmao.com/drama/Yy0wHDA=/episode'

设置请求头,模拟浏览器访问

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'

}

发送HTTP请求

response = requests.get(url, headers=headers)

response.raise_for_status() # 如果请求失败,将抛出异常

解析HTML

soup = BeautifulSoup(response.text, 'html.parser')

定位class="epipage clear"的div标签

div_epipage = soup.find('div', class_='epipage clear')

提取所有a标签的href值,并构成完整的网页下载URL

episode_links = []

for a_tag in div_epipage.find_all('a', href=True):

episode_url = 'https://www.tvmao.com' + a_tag['href']

episode_links.append(episode_url)

创建文件夹

d盘_qyn文件夹路径 = 'D:\\qyn'

if not os.path.exists(d盘_qyn文件夹路径):

os.makedirs(d盘_qyn文件夹路径)

下载并保存每个剧集的文本内容

for episode_url in episode_links:

print(f'正在下载:{episode_url}')

发送HTTP请求

episode_response = requests.get(episode_url, headers=headers)

episode_response.raise_for_status()

解析HTML

episode_soup = BeautifulSoup(episode_response.text, 'html.parser')

解析文件名

epi_t = episode_soup.find('p', class_='epi_t')

file_name = epi_t.text.strip().replace(':', '').replace('/', '-').replace('\\', '-').replace('|', '-') # 处理文件名

解析文本内容

epi_c = episode_soup.find('article', class_='clear epi_c')

text_content = epi_c.get_text(strip=True)

保存到txt文档

file_path = os.path.join(d盘_qyn文件夹路径, file_name + '.txt')

with open(file_path, 'w', encoding='utf-8') as file:

file.write(text_content)

print(f'已保存:{file_path}')

随机暂停1-10秒

time.sleep(random.randint(1, 10))

print('所有剧集文本已下载完毕。')

相关推荐
吴秋霖3 天前
主流反爬虫、反作弊防护与风控对抗手段
爬虫·算法·反爬虫技术
hui函数3 天前
scrapy框架-day02
后端·爬虫·python·scrapy
用户051610461674 天前
爬虫 API 技术全解析:从原理到实战的高效数据采集指南
爬虫·api
xiaoxiongip6665 天前
动态ip适合挂什么项目
网络·爬虫·python·网络协议·tcp/ip·ip
q567315236 天前
自动化拨号爬虫体系:虚拟机集群部署与增量管理
运维·爬虫·网络协议·自动化
电商API_180079052476 天前
淘宝商品视频批量自动化获取的常见渠道分享
java·爬虫·自动化·网络爬虫·音视频
果壳~7 天前
【Python】爬虫html提取内容基础,bs4
爬虫·python·html
jay神7 天前
基于Python的商品爬取与可视化系统
爬虫·python·数据分析·毕业设计·可视化系统
华科云商xiao徐7 天前
如何在C语言环境中借助Linux库构建高效网络爬虫
爬虫·数据挖掘·数据分析
明远湖之鱼7 天前
巧用 Puppeteer + Cheerio:批量生成高质量 Emoji 图片
前端·爬虫·node.js