【问题标题】:A Random Wikipedia Article Generator一个随机的维基百科文章生成器
【发布时间】:2021-07-30 20:24:09
【问题描述】:

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

代码:

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

【问题讨论】:

    标签: python api wikipedia


    【解决方案1】:

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

    【讨论】:

    • 它可以完成这项工作,但它不会以这种方式准确搜索
    猜你喜欢
    • 2012-01-31
    • 2022-01-23
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2015-07-05
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多