首页 > 解决方案 > 一个随机的维基百科文章生成器

问题描述

我有这个我创建的随机维基百科文章生成器,但我希望它会生成一篇关于特定主题的文章,并且由于某种原因,它会生成文章,但不会生成关于我输入的主题的文章。

代码:

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")

标签: pythonapiwikipedia

解决方案


根据: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}")

推荐阅读