import requests import json import re from bs4 import BeautifulSoup from datetime import…
- User
import requests import json import re from bs4 import BeautifulSoup from datetime import datetime
class Main():
codedef __init__(self) -> None: pass def fetch(self, url) -> str: headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'user-agent': 'application/json, text/javascript, */*; q=0.01', } r = requests.get(url, headers=headers) r.raise_for_status() r.encoding = r.apparent_encoding return r.text def getDailyNews(self) -> list[dict[str, str | list[dict[str, str]]]]: # yyyy-mm-dd 格式化当天日期 formatted_date = datetime.now().strftime("%Y-%m-%d") naviUrl = f'https://www.shobserver.com/staticsg/data/journal/{formatted_date}/navi.json' try: naviData = json.loads(self.fetch(naviUrl)) newsPages = naviData["pages"] print(f'「解放日报」正在处理 {formatted_date} 的 {len(newsPages)} 版新闻...') news = [] for newsPage in newsPages: pageName = newsPage["pname"] pageNo = newsPage["pnumber"] articleList = newsPage["articleList"] print( f'「解放日报」{pageNo} 版 - {pageName} 共有 {len(articleList)} 条新闻') for article in articleList: title = article["title"] subtitle = article["subtitle"] aid = article["id"] # 使用正则丢弃 title 含有广告的文章 if re.search(r'广告', title): continue articleContent, articlePictures = self.getArticle( formatted_date, pageNo, aid) news.append({ "id": f'{formatted_date}_{pageNo}-{aid}', "title": title, "subtitle": subtitle, "content": articleContent, "pictures": articlePictures }) return news except Exception as e: print(f'「解放日报」新闻列表获取失败!\n{e}') return [] def getArticle(self, date, pageNo, aid) -> tuple[str, list[object]]: articleUrl = f'https://www.shobserver.com/staticsg/data/journal/{date}/{pageNo}/article/{aid}.json' articleData = json.loads(self.fetch(articleUrl))["article"] articleContent = BeautifulSoup(articleData["content"], 'html.parser') # 转换 <br> 为 \n for br in articleContent.find_all("br"): br.replace_with("\n") articlePictures = [] articlePictureJson = json.loads(articleData["pincurls"]) for articlePicture in articlePictureJson: url = articlePicture["url"] name = articlePicture["name"] author = articlePicture["author"] ttile = articlePicture["ttile"] articlePictures.append({ "url": url, "alt": ttile, "title": ttile, "source": name, "author": author }) print( f'「解放日报」已解析 {pageNo} 版 - {articleData["title"]} | 字数 {len(articleContent)} | 图片 {len(articlePictures)} 张' ) return articleContent.get_text(), articlePictures - Assistant
这个错误说明在代码中使用了不支持的运算符"|". 在这种情况下,错误出现在行46,当尝试返回一个类型为"list[dict[str, str | list[dict[str, str]]]]"的值时出现了问题。
解决这个问题可以通过将类型注释中的"|"替换为Union,以表示可能的多种类型。修改line 46的代码如下:
pythondef getDailyNews(self) -> list[dict[str, Union[str, list[dict[str, str]]]]]: # remaining code这样就可以解决这个类型错误了。
- User
NameError: name 'Union' is not defined
- Assistant
在该代码中,Union类型是可选类型,需要从
typing模块导入才能使用。请更新您的代码并添加Union导入语句。将line 3的代码修改如下:pythonfrom typing import Union然后再运行代码,应该就能够解决这个错误了。
- User
ModuleNotFoundError: No module named 'undetected_chromedriver'
- Assistant
这个错误说明您的Python环境中缺少
undetected_chromedriver模块。undetected_chromedriver是一个用于驱动Chrome浏览器的库,您需要先安装它才能在代码中使用。您可以使用以下命令使用pip安装
undetected_chromedriver:shellpip install undetected_chromedriver安装完成后,再次运行代码,应该就能够解决这个错误了。