try-except-else中的循环问题

时间:2019-08-11 14:56:06

标签: python-3.x

我有一个作者和书籍列表,并且正在使用API​​来检索它们各自的描述和等级。我无法迭代列表并将说明存储在新列表中。

Goodreads API使我有机会查找书籍的信息,以准确性发送书名和作者,或者只发送书名。我想要的是:

  1. 环绕标题和作者的列表,获取第一标题和第一作者,然后尝试检索描述并将其保存在第三列表中。
  2. 如果找不到,请尝试仅使用标题检索描述并将其保存到列表中。
  3. 如果尚未找到,请添加标准错误消息。

我尝试了下面的代码,但无法迭代整个列表并保存结果。

#Running the API with author's name and book's title
book_url_w_author = 'https://www.goodreads.com/book/title.xml?author='+edit_authors[0]+'&key='+api_key+'&title='+edit_titles[0]

#Running the API with only book's title
book_url_n_author = 'https://www.goodreads.com/book/title.xml?'+'&key='+api_key+'&title='+edit_titles[0]

# parse book url with author
html_n_author = requests.get(book_url_w_author).text
soup_n_author = BeautifulSoup(html_n_author, "html.parser")

# parse book url without author
html_n_author = requests.get(book_url_n_author).text
soup_n_author = BeautifulSoup(html_n_author, "html.parser")

#Retrieving the books' descriptions
description = []

try:
    #fetch description for url with author and title and add it to descriptions list
    for desc_w_author in soup_w_author.book.description:
        description.append(desc_w_author)
except:
    #fetch description for url with only title and add it to descriptions list
    for desc_n_author in soup_n_author.book.description:
        description.append(desc_n_author)
else:
    #return and inform that no description was found
    description.append('Description not found')

Expected:
description = [description1, description2, description3, ....]

0 个答案:

没有答案