python - 一个随机的维基百科文章生成器
问题描述
我有这个我创建的随机维基百科文章生成器,但我希望它会生成一篇关于特定主题的文章,并且由于某种原因,它会生成文章,但不会生成关于我输入的主题的文章。
代码:
import requests
from bs4 import BeautifulSoup
import webbrowser
while True:
topic = input("Plz enter a topic you would like to read about: ")
url = requests.get(f"https://en.wikipedia.org/wiki/Special:Random/{topic}")
soup = BeautifulSoup(url.content, "html.parser")
title = soup.find(class_="firstHeading").text
answer = input(f"The article is: {title} \nWould you like to view this article? (Y/N)\n").upper()
if answer == "Y":
url = "https://en.wikipedia.org/wiki\%s" %title
webbrowser.open(url)
leave = input("Would you like to read another one? (Y/N)\n").upper()
if leave == "Y":
pass
else:
break
elif answer == "N":
print("Try again!!")
else:
print("I don't know what it is")
解决方案
根据:https ://en.wikipedia.org/wiki/Wikipedia:Special:Random
分类随机主题的端点是: https ://en.wikipedia.org/wiki/Special:RandomInCategory/
而不是: https ://en.wikipedia.org/wiki/Special:Random/
因此,您应该将您的网址更改为:
url = requests.get(f"https://en.wikipedia.org/wiki/Special:RandomInCategory/{topic}")
推荐阅读
- boto3 - 如何使用 Boto3 仅从 s3 存储桶获取文件名
- excel - 在 Excel VBA 中单击按钮后切换单元格值
- python - 不能让我的第一个蜘蛛运行,有什么建议吗?
- python - 如何在多输出回归中获得每个输出的损失?
- python - 使用 setup.py 安装远程 tar 依赖
- rust - 映射`ndarray::Array`时,如何用`?`替换`.unwrap()`?
- c# - 即使使用 HasKey 来标识主键,Entity Framework 中的 Code-First 方法是否总是创建一个 Id 字段?
- amazon-web-services - AWS Lambda 函数未运行完成
- css - 当用户增加浏览器文本大小时如何防止图像大小调整
- xslt - xslt1.0 将 dateTime 转换为 YYYY/MM/DD