有些播客会在官网上放出已经转录好的文本,比如MIT Technology Review:
https://www.technologyreview.com/supertopic/in-machines-we-trust/
怎么批量下载这些播客文本呢?
在deepseek中输入提示词:
你是一个Python编程专家,要完成一个批量爬取网页的任务,具体步骤如下:
打开网页:https://www.technologyreview.com/supertopic/in-machines-we-trust/
定位所有class="postGrid__wrapper--a743d3c2e1bf8f32f117f0bf0cdde374"的div标签;
在div标签中定位第1个a标签,提取其href属性值,这个一个网页URL;
打开这个网页,保存到文件夹F:\in-machines-we-trust,网页格式为html;
注意:每一步都要输出信息到屏幕上
标题:class="contentArticleHeader__title--4ba85d49e1a4385c0496cbbb5900641b"
源代码:
import requests
from bs4 import BeautifulSoup
import os
# 定义目标网页的URL
url = "https://www.technologyreview.com/supertopic/in-machines-we-trust/"
# 定义保存文件的文件夹路径
save_folder = "F:\\in-machines-we-trust"
# 确保保存文件的文件夹存在
if not os.path.exists(save_folder):
os.makedirs(save_folder)
print(f"Created folder: {save_folder}")
# 第一步:打开网页
print(f"Opening webpage: {url}")
response = requests.get(url)
response.raise_for_status() # 检查请求是否成功
# 第二步:解析HTML
print("Parsing HTML...")
soup = BeautifulSoup(response.text, 'html.parser')
# 第三步:定位所有class="postGrid__wrapper--a743d3c2e1bf8f32f117f0bf0cdde374"的div标签
divs = soup.find_all('div', class_="postGrid__wrapper--a743d3c2e1bf8f32f117f0bf0cdde374")
print(f"Found {len(divs)} divs with the specified class.")
# 第四步:在每个div标签中定位第1个a标签,提取其href属性值
for i, div in enumerate(divs):
a_tag = div.find('a')
if a_tag:
href = a_tag.get('href')
print(f"Extracted URL {i+1}: {href}")
# 第五步:打开这个网页,保存到文件夹
article_response = requests.get(href)
article_response.raise_for_status()
# 生成保存文件的文件名
filename = os.path.join(save_folder, f"article_{i+1}.html")
# 保存网页内容到文件
with open(filename, 'wb') as file:
file.write(article_response.content)
print(f"Saved article {i+1} to {filename}")
else:
print(f"No 'a' tag found in div {i+1}")
print("Task completed.")
代码解释:
打开网页:使用requests.get(url)发送HTTP GET请求,获取网页内容。
解析HTML:使用BeautifulSoup解析获取到的HTML内容。
定位div标签:使用soup.find_all('div', class_="postGrid__wrapper--a743d3c2e1bf8f32f117f0bf0cdde374")找到所有符合条件的div标签。
提取href属性:在每个div标签中找到第一个a标签,并提取其href属性值。
保存网页:使用requests.get(href)获取目标网页的内容,并将其保存到指定文件夹中。
注意事项:
确保目标网页的结构没有变化,否则可能需要调整选择器。
如果目标网页需要登录或使用JavaScript动态加载内容,可能需要使用Selenium等工具。
如果目标网页有反爬虫机制,可能需要添加请求头或使用代理。
运行这个脚本后,你会在F:\in-machines-we-trust文件夹中看到保存的HTML文件。
本文分享自 Dance with GenAI 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!