零代码编程:用ChatGPT批量下载某个网页中的特定网页链接
  6ZTWmbGzfXvY 2023年11月30日 16 0

以lexfridman的官方网站为例,https://lexfridman.com/podcast/,如何批量下载网页呢?

零代码编程:用ChatGPT批量下载某个网页中的特定网页链接_文件名

零代码编程:用ChatGPT批量下载某个网页中的特定网页链接_文件名_02

查看网页源文件,播客transcript的链接是:

<a href="https://lexfridman.com/jared-kushner-transcript">Transcript</a>

文件标题在这里:<title>Transcript for Jared Kushner: Israel, Palestine, Hamas, Gaza, Iran, and the Middle East | Lex Fridman Podcast #399 - Lex Fridman</title>

所以,在ChatGPT中输入提示词如下:

你是一个Python编程专家,要完成一个批量下载网页的任务,具体步骤如下:

在本地电脑D盘新建一个文件夹:lexfridman-podtext;

打开网页https://lexfridman.com/podcast/,解析网页源代码;

提取网页源代码中所有<a>标签的内容;

如果<a>标签的内容为“Transcript”,就提取<a>标签的href属性值,作为网页下载地址;

然后解析这个网页源代码,提取其<title>标签内容,作为网页的文件标题名;

下载这个网页,保存到文件夹lexfridman-podtext;

注意:<title>标签内容提取后,要将其中的“: ”、“ | ”等Windows系统中不允许作为文件名的特殊符号替换为符号”-”;

每一步都要输出相关信息;

ChatGPT生成源代码如下:

import os

import requests

from bs4 import BeautifulSoup

# 函数用于清理文件名中的非法字符

def clean_filename(filename):

return filename.replace(':', '-').replace('|', '-')

# 在D盘新建文件夹

folder_path = "D:\\lexfridman-podtext"

if not os.path.exists(folder_path):

os.makedirs(folder_path)

print(f"新建文件夹:{folder_path}")

# 打开并解析网页

source_url = "https://lexfridman.com/podcast/"

print(f"打开并解析网页:{source_url}")

response = requests.get(source_url)

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

# 提取所有<a>标签

a_tags = soup.find_all('a')

# 遍历<a>标签,找出内容为“Transcript”的

for a_tag in a_tags:

if a_tag.text == "Transcript":

# 提取<a>标签的href属性值

href = a_tag['href']

print(f"找到Transcript网页地址:{href}")

# 打开并解析Transcript网页

transcript_response = requests.get(href)

transcript_soup = BeautifulSoup(transcript_response.text, 'html.parser')

# 提取<title>标签内容

title_tag = transcript_soup.find('title')

if title_tag:

title = clean_filename(title_tag.text)

print(f"找到Transcript网页标题:{title}")

# 下载网页并保存到文件

filename = os.path.join(folder_path, title + ".html")

with open(filename, 'w', encoding='utf-8') as f:

f.write(transcript_response.text)

print(f"网页已保存到:{filename}")

零代码编程:用ChatGPT批量下载某个网页中的特定网页链接_文件名_03

运行程序,全部网页下载保存到本地:

零代码编程:用ChatGPT批量下载某个网页中的特定网页链接_批量下载_04

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月30日 0

暂无评论

推荐阅读
6ZTWmbGzfXvY