【问题标题】:Failed attempts to read XML from goodreads API using requests and lxml使用 requests 和 lxml 从 goodreads API 读取 XML 的尝试失败
【发布时间】:2019-02-03 04:29:54
【问题描述】:

Goodreads 声称我可以获得以名为 <GoodreadsResponse> 的根开头的 XML,其第一个孩子是 <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 

【问题讨论】:

    标签: python xml api python-requests lxml


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      这是最适合我的解决方案:

      导入请求 从 bs4 导入 BeautifulSoup

      def main():
          key = 'myKey'
          isbn = '0441172717'
          url = 'https://www.goodreads.com/book/isbn/{}?key={}'.format(isbn, key)
          response = requests.get(url)
          soup = BeautifulSoup(response.content, "lxml-xml")
          print(soup.find('image_url').text)
      

      问题在于 XML 内容被包装在标签中。使用 Beautiful Soup 'lxml-xml' 解析器,而不是 'lxml' 保留 CDATA 标记中包含的内容并允许它们被正确解析。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-31
        • 1970-01-01
        • 2017-03-19
        • 2018-01-03
        • 2017-05-19
        • 1970-01-01
        相关资源
        最近更新 更多