分享

AI网络爬虫:kimi批量爬取《庆余年》分集剧情

 AIGC部落 2024-05-24 发布于广东

先找到每集的链接地址,都在这个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('所有剧集文本已下载完毕。')

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约