【问题标题】:Dynamically parsing the q as an user input to search news in News API in python动态解析 q 作为用户输入以在 python 中的 News API 中搜索新闻
【发布时间】:2020-12-06 15:00:18
【问题描述】:

我已经编写了搜索特定关键字并通过新闻 API 提供新闻的代码,但我已经硬编码了 q (要在文章标题和正文中搜索的关键字或短语。)但我希望它应该是动态的,就像用户提供关键字进行搜索一样,它提供了一切。谁能帮帮我吗。 下面是我正在做的代码sn-p。

import requests
url = ('http://newsapi.org/v2/everything?'
       'q=Python&'
       'from=2020-08-17&'
       'sortBy=popularity&'
       'apiKey=xxxxxxx')

response = requests.get(url)

【问题讨论】:

标签: python python-3.x python-requests


【解决方案1】:

希望这能解决您的问题,

import requests
What=input("Enter the q: ")
url = ('http://newsapi.org/v2/everything?'
       f'q={What}'
       'from=2020-08-17&'
       'sortBy=popularity&'
       'apiKey=xxxxxxx')

response = requests.get(url)

此代码将要求用户输入 q,将其存储在“What”变量中,因此可以动态更改

【讨论】:

  • 谢谢@Nikhil 我在您提供的解决方案中遇到了小树枝的错误并且它有效。为更广泛的受众导入请求发布它 What=input("Enter the q: ") url = ('newsapi.org/v2/everything?' 'q='+What+'&' 'from=2020-08-17&' 'sortBy=popularity&' 'apiKey=XXXXXXXXXX')
猜你喜欢
  • 2017-02-27
  • 1970-01-01
  • 2020-03-26
  • 2019-07-01
  • 2017-10-17
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
相关资源
最近更新 更多