获取json负载,然后用python剥离html



我有一个json值,需要去掉所有html标记。

使用以下功能后:

def payloaded():
from urllib.request import urlopen
with urlopen("www.example.com/payload.json") as r:
    data = json.loads(r.read().decode(r.headers.get_content_charset("utf-8")))
text = (data["body"]["und"][0]["value"])
return(text)

这是返回的(文本):

&lt;div class=&quot;blah&quot;&gt;'<p>This is the text.</p>rn'

这是原件(文本):

<div class="blah"><p>This is the text.</p>

注意:我需要去掉所有的html标签,并且没有关于我将得到什么标签的真正指导方针。

这就是我想要的(文本):

This is the text.

这是我正在使用的post函数:

def add_node_basic(text)
url = "www.example.com"
headers = {"content-type": "application/json"}
payload = {
    "auth_token": x,
    "docs":
        {
            "id": y,
            "fields": [
                {"name": "body", "value": text, "type": "text"},
            ]}
}
r = requests.post(url, data=json.dumps(payload), headers=headers)

任何关于如何实现这一目标的建议都将不胜感激!

您可以尝试将字符串与find方法一起切片,如下所示:

>>> print text[text.find('<p>'):text.find('</p>')].strip('<p>')
This is the text.

如果您试图只从HTML源代码中提取文本,那么您可以使用Python中的HTMLParser库。示例:

from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)
def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

最新更新