gpt4 book ai didi

python - lxml 在解析之前不会将 int 强制转换为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:10 25 4
gpt4 key购买 nike

我正在尝试使用 python 从 API 调用中提取 Qualys 漏洞报告 ID。本质上,报告ID是一个int,而lxml只能解析字符串。我过去曾使用相同的代码来执行此操作,并且效果很好。我假设 lxml 足够聪明,可以在解析之前将 int 强制转换为 string 。有什么方法可以手动执行此操作,这样我就不再收到解析错误了吗?下面是我的代码、输出和回溯。

代码:

import requests
import time
import lxml
from lxml import etree

s = requests.Session()
s.headers.update({'X-Requested-With':'X'})

def login(s):
payload = {'action':'login', 'username':'X', 'password':'X'}

r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/',
data=payload)

def launchReport(s, polling_delay=250):
payload = {'action':'launch', 'template_id':'X',
'output_format':'xml', 'report_title':'X'}

r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/',
data=payload)
print r.text
extract_id = etree.XML(r).find('.//VALUE')
print("Report ID = %s" % extract_id)
time.sleep(polling_delay)
return extract_id

login(s)
launchReport(s)

输出:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE SIMPLE_RETURN SYSTEM
"https://qualysapi.qualys.com/api/2.0/simple_return.dtd">
<SIMPLE_RETURN>
<RESPONSE>
<DATETIME>2018-02-01T16:00:14Z</DATETIME>
<TEXT>New report launched</TEXT>
<ITEM_LIST>
<ITEM>
<KEY>ID</KEY>
<VALUE>16441920</VALUE>
</ITEM>
</ITEM_LIST>
</RESPONSE>
</SIMPLE_RETURN>

回溯:

Traceback (most recent call last):
File "test.py", line 30, in <module>
launchReport(s)
File "test.py", line 22, in launchReport
extract_id = etree.XML(r).find('.//VALUE')
File "src/lxml/etree.pyx", line 3209, in lxml.etree.XML
(src/lxml/etree.c:80823)
File "src/lxml/parser.pxi", line 1870, in
lxml.etree._parseMemoryDocument (src/lxml/etree.c:121231)
ValueError: can only parse strings

最佳答案

您正在尝试解析响应对象而不是响应中的数据。将 etree.XML(r) 更改为 etree.XML(r.text)

关于python - lxml 在解析之前不会将 int 强制转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48567259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com