有些播客会在官网上放出已经转录好的文本,比如MIT Technology Review:
https://www.
technologyreview.com/su
pertopic/in-machines-we-trust/
怎么批量下载这些播客文本呢?
在deepseek中输入提示词:
你是一个Python编程专家,要完成一个批量爬取网页的任务,具体步骤如下:
打开网页:
https://www.
technologyreview.com/su
pertopic/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/su
pertopic/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)