【问题标题】:Python how to add more than one input in the requests.get urlPython如何在requests.get url中添加多个输入
【发布时间】:2021-01-25 16:02:17
【问题描述】:

我目前作为初学者正在做一个网页抓取歌词项目,我遇到了一个问题。

我希望用户输入艺术家姓名的第一个字母和完整的艺术家姓名,但我不太确定如何处理 URL 中的斜杠。代码如下:

from bs4 import beautifulSoup as bs
import requests


    def main():
        lyrics_getter()
    
    
    def artist_input():
        first_artist_name = input(
            "Please enter the first letter of the artists name: ")
    
        artist_name = input("Please enter the name of an artist: ")
        if not artist_name.isalpha():
            print("Please enter only alphabetical characters for the artist.")
        else:
            print(artist_name)
            print("Compiling lyrics for: ", artist_name,
                  sep="")
    
    
    def lyrics_getter():
    
        artist_input()
        website = requests.get('https://www.azlyrics.com/',
                               first_artist_name, '/', artist_name, '.html') # ERROR OCCURS HERE
    
    
    if __name__ == '__main__':
        main()

lyrics_getter() 函数中,我尝试在 url 中使用来自 artist_input() 的用户输入,但出现意外的参数错误。

我认为这主要是由于我拆分了网址,但我不确定如何去做。这是我想要实现的一个示例:

https://www.azlyrics.com/j/jayz.html

有什么建议吗?

谢谢!

【问题讨论】:

  • 而不是 , 将多个参数传递给 requests.get() 使用 + 连接字符串,或者我们 os.path.join()
  • 'https://www.azlyrics.com/' + first_artist_name + '/' + artist_name + '.html'

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

有无数种方法可以做到这一点,我首选的方法是将 f 放在 string 方法之前,因为它在我看来是最干净的。

将“f”放在字符串前面,并使用 {} 将变量直接放入字符串中。

website = requests.get(f'https://www.azlyrics.com/{first_artist_name}/{artist_name}.html')

我希望有另一种选择会有所帮助:)

【讨论】:

  • 谢谢!有其他选择肯定很好。
【解决方案2】:

在python中你可以使用format()函数。

'https://www.azlyrics.com/{}/{}.html'.format(first_artist_name,artist_name)

所以理想情况下你的代码应该是

website = requests.get('https://www.azlyrics.com/{}/{}.html'.format(first_artist_name,artist_name)) 

【讨论】:

    【解决方案3】:

    我会使用f string 方法!

    website = requests.get(f'https://www.azlyrics.com/{first_artist_name}/{artist_name}.html')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2020-10-13
      • 1970-01-01
      相关资源
      最近更新 更多