【问题标题】:Retrieving page content from Confluence REST with Python and Pandas使用 Python 和 Pandas 从 Confluence REST 中检索页面内容
【发布时间】:2019-05-22 16:28:08
【问题描述】:

我想计算我的知识库中在 Confluence 上运行的页面上的单词统计信息。

但在进行计算之前,我想检索页面数据:页面上写入的文本。

我有一个最初用于从页面收集评论的 Python 脚本。 我正在尝试为我在 Confluence REST 浏览器中找到的 /rest/api/content/{id} REST API 调整脚本。

原始脚本使用 API 将结果作为 JSON 对象返回,当使用 json() 方法解析时返回字典对象。

但是,/rest/api/content/{id} API 返回的结果不包含格式正确的字典。我收到字符串对象,我不能简单地将它们寻址为 array['index'] = result ['value'] 来检索页面数据。

我正在使用 JupyterLab 环境运行代码。

在页面 4068365 使用 Confluecne Browser 和 /rest/api/content/{id} API 时,Confluence 返回如下结果:

{
  "id": "4068365",
  "type": "page",
  "status": "current",
  "title": "Page title",
  "body": {
    "view": {
      "value": "<p>Some text</p>",
      "representation": "storage",
      "_expandable": {
        "webresource": "",
        "content": "/rest/api/content/4068365"
      }
    },
    "_expandable": {
      "editor": "",
      "export_view": "",
      "styled_view": "",
      "storage": "",
      "anonymous_export_view": ""
    }
  },
  "extensions": {
    "position": "none"
  },

...

我想获取 'value' 键的值。但是,'value' 参数不会被识别为键,因为结果被格式化为字符串而不是字典。

这是我的代码。


import requests
import json
import getpass
import re
import html
import pandas as pd
from datetime import datetime

# Allow HTTPS connections with self-signed cert
requests.packages.urllib3.disable_warnings()

# Create login session for Confluence
auth = ('mylogin', getpass.getpass())
s = requests.Session()
s.auth = auth
s.verify = False
s.headers = {"Content-Type": "application/json"}

# Confluence REST API URI
WIKI = 'https://example.net/wiki/rest/api/'

# Obtain text from Confluence HTML layout
def cleanhtml(raw_html):
    cleanr = re.compile('<.*?>')
    text = html.unescape(raw_html)
    text = re.sub(cleanr, '', text)
    text = text.replace(u'\xa0', u' ')
    return text

# Retrieving page data
def get_data(page_id):
    data = []
    r = s.get(
     '{}content/{}'.format(WIKI, page_id),
      params = dict(
       expand='body.view'
       )      
    )
    for content in r.json():
        pgdata = dict()
#I can't address to value as content['value']
        pgdata['text'] = cleanhtml(content['body']['view'].get('value'))
        data.append(pgdata)            
   return data

# Pages to extract from
with open(r'C:\\Users\\Stacy\\Documents\\pages.txt') as pagesf:
     pagesl = pagesf.read()
pages = pagesl.split(",\n")        
print(pages)

# Preparing data frame and exporting to Excel
textdata = list()
for page in pages:
    print('Handing:', page)
    textdata.extend(get_data(page))

df = pd.DataFrame(
    textdata, 
    columns = ['text']
)

df.to_excel('page_data{}.xlsx'.format(datetime.now().strftime("%Y_%m_%d_%H-%M")))

我想收集来自

的文本
 "value": "<p>Some text</p>",

到数据中并将所有内容存储在字典中。但是,我看到内容包含数据类型而不是数据,所以我不能将“body”作为键引用,因为它不是键。

请帮我从“价值”中检索页面数据。什么是正确的方法?谢谢。

【问题讨论】:

    标签: python jupyter-notebook confluence-rest-api


    【解决方案1】:

    这是我找到的解决方案:

    
    def get_words(page_id):
        comments = []
        r = s.get(
          '{}content/{}'.format(WIKI, page_id),
            params = dict(
               expand='body.view'
               )      
            )
        for cmnt in r: # No valid json, so we scan the result
            comments.append(cmnt) # Collect all strings into a list
            bytes = [] #Results are encoded, store decoded data in a list
            for byte in comments:
                byted = byte.decode('utf-8', 'ignore') #Decode as UTF-8 and ignore errors
                bytes.append(byted)
        bytesstr = "".join(bytes) # List contains split strings, join them together into a single line
        parsed = json.loads(bytesstr); # Convert the line into a valid JSON object
        pgdata =  dict() # Preparing dictionary to store extracted text
        pgdata['value'] = parsed['body']['view'].get('value') # Retrieving text from the page
        pgdatac = cleanhtml(pgdata['value']) # Removing HTML tags
        counts = len(re.findall(r'\w+', pgdatac)) # Extra line to calculate words on a page
        print(counts)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多