修改这段代码并写出来import requests from bs4 import BeautifulSoup # 爬取的页面数量 num_pages = 5 # 打开每个页面并获取 HTML 内容 for page_num in range(1, num_pages + 1): url = f"https://www.bernama.com/bm/index.php/archive.php?page={page_num}" response = requests.get(url) html_content = response.text # 解析 HTML 内容,获取新闻标题和内容 soup = BeautifulSoup(html_content, "html.parser") news_list = soup.find_all("div", class_="row news-row") for news in news_list: title = news.find("a").text.strip() link = news.find("a")["href"] news_response = requests.get(link) news_html = news_response.text news_soup = BeautifulSoup(news_html, "html.parser") content_list = news_soup.find_all("div", class_="col-md-12 news-body") content = "\n".join([p.text for p in content_list[0].find_all("p")]) print(content) # 将新闻标题和内容保存到 txt 文件 with open(f"page{page_num}_{title}.txt", "w") as f: f.write(f"Title: {title}\n") f.write(f"Link: {link}\n") f.write(f"Content:\n{content}\n")
时间: 2024-03-07 18:53:21 浏览: 290
import requests
from bs4 import BeautifulSoup
# 爬取的页面数量
num_pages = 5
# 打开每个页面并获取 HTML 内容
for page_num in range(1, num_pages + 1):
url = f"https://www.bernama.com/bm/index.php/archive.php?page={page_num}"
response = requests.get(url)
html_content = response.text
# 解析 HTML 内容,获取新闻标题和内容
soup = BeautifulSoup(html_content, "html.parser")
news_list = soup.find_all("div", class_="row news-row")
for news in news_list:
title = news.find("a").text.strip()
link = news.find("a")["href"]
# 打开每个新闻链接并获取 HTML 内容
news_response = requests.get(link)
news_html = news_response.text
# 解析新闻 HTML 内容,获取新闻内容
news_soup = BeautifulSoup(news_html, "html.parser")
content_list = news_soup.find_all("div", class_="col-md-12 news-body")
content = "\n".join([p.text for p in content_list[0].find_all("p")])
# 将新闻标题和内容保存到 txt 文件
with open(f"page{page_num}_{title}.txt", "w") as f:
f.write(f"Title: {title}\n")
f.write(f"Link: {link}\n")
f.write(f"Content:\n{content}\n")
阅读全文