【问题标题】:How to save value from JSON as HTML code, not as a string, in python?如何在 python 中将 JSON 中的值保存为 HTML 代码,而不是字符串?
【发布时间】:2019-08-25 03:52:21
【问题描述】:

从网站获取 JSON 数据。这是它的一部分,我感兴趣。

...
"content":{  
         "rendered":"<p><img class=\"aligncenter size-full wp-image-91555\" src=\"https:\/\/ebook3000.biz\/wp-content\/uploads\/2019\/03\/Edge-May-2019.png\" alt=\"Edge - May 2019 \" width=\"226\" height=\"290\" \/><\/p>\n<p>English |PDF|80 MB<\/p>\n<div class=\"box download  \"><div class=\"box-inner-block\"><i class=\"fa tie-shortcode-boxicon\"><\/i>\n\t\t\t Download<\/p>\n<p><a href=\"https:\/\/dropupload.com\/T97\/2019-05-01_Edge.pdf\" target=\"_blank\" rel=\"nofollow\">https:\/\/dropupload.com\/T97\/2019-05-01_Edge.pdf<\/a><\/p>\n\n\t\t\t<\/div><\/div>\n",
         "protected":false
      },
      "excerpt":{  
         "rendered":"<p>English |PDF|80 MB<\/p>\n",
         "protected":false
      },
      "author":1...

想要从 [content][rendered] 中获取值作为 HTML 代码,以便在 xpath 中使用它。想要获取“dropupload”链接的href值。

这是我现在保存这个值的 scrapy spider 中的代码:

content = mag['content']['rendered']

但它保存为“str”。怎么可能得到HTML?

非常感谢!

【问题讨论】:

  • 但是 HTML 可以存储在字符串中,是的。您究竟需要什么数据类型?
  • 我想在 xpath 中使用这个 html。而且我不确定我应该如何保存这个值以供将来使用 xpath 表达式进行处理。不管是哪种格式)
  • 尝试对保存的值使用 .xpath() - 得到回溯“AttributeError: 'str' object has no attribute 'xpath'”
  • 基本上这家伙想要的是没有转义字符的普通 html 代码......

标签: python json scrapy


【解决方案1】:

所以,您的 HTML 中有字符串。然后你可以在单独的选择器中使用它,比如这里:

from scrapy import Selector
sel = Selector(text=mag['content']['rendered'])
print sel.css('a::attr(href)').get()  # or your css/xpath selector here

【讨论】:

  • 哇!谢啦!它有助于!我已经花了 4 个小时试图弄清楚该怎么做)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多