首页 > 解决方案 > 使用 requests 和 lxml 从 goodreads API 读取 XML 的尝试失败

问题描述

Goodreads 声称我可以得到以名为的根开头的 XML <GoodreadsResponse>,它的第一个孩子是<book>,第八个孩子是image_url。麻烦的是,我无法让它识别正确的根(它root不会打印GoodreadsResponse并且根本无法识别根有任何孩子,尽管响应代码是 200。我更喜欢使用 JSON,据称,你可以将其转换为 JSON,但我的运气为零。

这是我目前拥有的功能。我哪里错了?

def main(url, payload):
    """Retrieves image from Goodreads API endpoint returning XML response"""
    res = requests.get(url, payload)
    status = res.status_code
    print(status)
    parser = etree.XMLParser(recover=True)
    tree = etree.fromstring(res.content, parser=parser)
    root = etree.Element("root")
    print(root.text)

if __name__ == '__main__':
    main("https://www.goodreads.com/book/isbn/", '{"isbns": "0441172717", "key": "my_key"}')

goodreads 信息在这里:

**Get the reviews for a book given an ISBN**
Get an xml or json response that contains embed code for the iframe reviews widget that shows excerpts (first 300 characters) of the most popular reviews of a book for a given ISBN. The reviews are from all known editions of the book. 
URL: https://www.goodreads.com/book/isbn/ISBN?format=FORMAT    (sample url) 
HTTP method: GET 

标签: pythonxmlapipython-requestslxml

解决方案


目前,您收到的请求是 HTML 而不是 XML。您需要设置所需响应的格式:https://www.goodreads.com/book/isbn/ISBN?format=FORMAT

你需要使用参数而不是有效负载: Constructing requests with URL Query String in Python

PS 对于您正在执行的请求,您可以使用 JSON。 https://www.goodreads.com/api/index#book.show_by_isbn


推荐阅读