我在脚本中使用requests.put()方法自动更新网页。问题是自动化脚本并不像应该的那样完全自动化。让我向您展示导致此问题的代码片段:
import requests
import json
from requests.auth import HTTPBasicAuth
from bs4 import BeautifulSoup
headers = {
'Content-Type': 'application/json',
}
# Just a string payload being extracted from previous lines of code not shown here
pass_string = str(soup).replace('\"', '\\"')
data = '{"id":"525424594","type":"page", "title":"Update status","space":{"key":"CSSAI"},"body":{"storage":{"value":"' + pass_string + '","representation":"storage"}}, "version":{"number":44}}'
response = requests.put('https://confluence.ai.com/rest/api/content/525424594', headers=headers, data=data,
auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai'))因此,在名为data的JSON字符串中,我们有一个名为"version":{"number":44}的键,用于更新网页,使我们在页面版本方面没有任何冲突。而且,每次网页内容发生变化时,都应该更新。有两种情况将改变网页的“版本”:
对于案例1,我可以有一个.txt文件,它将记录网页的前一个版本,这样每当我执行脚本时,我就可以从.txt文件中读取上一个版本,并且该版本在脚本中自动增加1,将该版本写入.txt文件,并使用递增版本执行命令。但是对于第二种情况,我不知道是否有人改变了网页本身的版本,所以很难知道该网页的当前版本。对我如何解决这个问题有什么想法吗?
发布于 2021-05-03 19:09:33
经过思考,我找到了所需的解决方案。如果有人有更好的解决方案,请张贴在这里。
import requests
import json
from requests.auth import HTTPBasicAuth
from bs4 import BeautifulSoup
headers = {
'Content-Type': 'application/json',
}
# Just a string payload being extracted from previous lines of code not shown here
pass_string = str(soup).replace('\"', '\\"')
data = '{"id":"525424594","type":"page", "title":"Update status","space":{"key":"CSSAI"},"body":{"storage":{"value":"' + pass_string + '","representation":"storage"}}, "version":{"number":2}}'
response = requests.put('https://confluence.ai.com/rest/api/content/525424594', headers=headers, data=data,
auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai'))
if response.json()["statusCode"] == 409:
error_message = "Version must be incremented on update. Current version is: "
if error_message in response.json()["message"]:
current_version = response.json()["message"].split(error_message)[1]
version_num = int(current_version) + 1
data = '{"id":"525424594","type":"page", "title":"Update Status","space":{"key":"CSSAI"},"body":{"storage":{"value":"' + pass_string + '","representation":"storage"}}, "version":{"number":' + str(
version_num) + '}}'
response = requests.put('https://confluence.ai.com/rest/api/content/525424594', headers=headers, data=data,
auth=HTTPBasicAuth('svc-Automation@ai.com', 'AIengineering1@ai'))
else:
print(response.json())
sys.exit(1)基本上,我从失败的响应中收集当前版本号,并将其增量为一个,以发送新请求。然而,这确实意味着我们的第一个请求总是失败的请求。
https://stackoverflow.com/questions/67373131
复制相似问题