如何为连续的webAPI调用更改一个XML标记的内容?

2024-05-20 15:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用ebayapi和Python的requests包。具体地说,我有一个ItemID的列表(大约10000左右),我从eBay的Finding API得到的,现在我想用这些id和TradingAPI来获得项目图像。 例如,这就是我请求的主体

xml = """<?xml version="1.0" encoding="utf-8"?><GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <Version>1085</Version>
  <RequesterCredentials>
    <eBayAuthToken>YourTokenhere</eBayAuthToken>
  </RequesterCredentials>
  <MessageID>XML call: OAuth Token in trading</MessageID>
   <DetailLevel>ItemReturnAttributes</DetailLevel>
  <ItemID>254140401476</ItemID><OutputSelector>Item.PictureDetails.PictureURL</OutputSelector>
  <IncludeItemSpecifics>false</IncludeItemSpecifics>
</GetItemRequest>"""

所以我的问题是: 使用每个API调用更改ItemID值的最有效方法/最佳实践是什么

我面临的一些问题:

  1. 我可以使用BeautifulSoup轻松地更改值,但是xml现在是BeautifulSoup对象。到目前为止,我还没有在BeautifulSoup中找到一种方法来转换回xml。我尝试过使用encode(“utf-8”),但这会在xml中添加新行

  2. 在Python请求模块文档中,他们说您可以直接提交dict,这将使值更容易更改。但我不知道如何将XML转换为dict,例如 <GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">标记。我也不确定eBay API是否会接受这个

  3. 我也尝试过使用xmltodict,但没有成功,这让我觉得ebayapi也不会接受这种格式的有序字典

  4. 我的首要问题是使用ElementTree(还没有尝试过这个,但那将是我的下一步)或BeautifulSoup将XML转换为树,然后再次尝试转换回来,这似乎是非常低效的

我感谢任何帮助或建议!谢谢你


Tags: apiversionxmlutfapisebayxmlnsbeautifulsoup
1条回答
网友
1楼 · 发布于 2024-05-20 15:27:53

如果我理解正确,您有一个项目ID列表,如:

item_ids = [254140401476,111140406666] #etc.

您希望xml中的元素<ItemID>依次填充每个元素,如果是这样,可以使用f字符串:

 for id in item_ids:
    print(f"""<?xml version="1.0" encoding="utf-8"?><GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <Version>1085</Version>
  <RequesterCredentials>
    <eBayAuthToken>YourTokenhere</eBayAuthToken>
  </RequesterCredentials>
  <MessageID>XML call: OAuth Token in trading</MessageID>
   <DetailLevel>ItemReturnAttributes</DetailLevel>
  <ItemID>{id}</ItemID><OutputSelector>Item.PictureDetails.PictureURL</OutputSelector>
  <IncludeItemSpecifics>false</IncludeItemSpecifics>
</GetItemRequest>""")

注意,<ItemID>元素现在包含变量<ItemID>{id}</ItemID>,而不是硬连线的项id

相关问题 更多 >