带有BeautifulSoup的Python XML数据

2024-05-28 22:41:30 发布

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

好的,我很难用Beautiful Soup过滤掉一些XML数据

以下是XML数据:

<ticket>
<id>123456789</id>
<create_date>2017-12-09</create_date>
- <correspondence>
   - <diary_entry>
     - <user>username</user>
     - <timestamp>2017-12-09</timestamp>
     - <body>A bunch of text in here
          a lot of text
          more text
     - </body>
   - </diary_entry>
- </correspondence>
- <work_log>
   - <diary_entry>
     - <user>someotheruser</user>
     - <timestamp>2017-12-09</timestamp>
     - <body>Some more text in here
             and other text
     - </body>
   - </diary_entry>
- </work_log>
</ticket

我试图只在通信/日记条目/正文部分中获取值,但我的代码也一直在worklog/日记条目/正文部分中提供值。这是我目前的代码:

ticket_url = "https://somelink/tickets/123456789"
    r = requests.get(ticket_url, auth=HTTPBasicAuth('username', 'password'))
    soup = BeautifulSoup(r.content,'xml')
    updates = soup.findAll('body')
    for update in updates:
        if "next steps:" not in update.text.lower():
            print "no"
            print update.text.lower()
        else:
            print "yes"

我不知道如何过滤它,只得到<correspondence><body>值。非常感谢您的帮助


Tags: 数据textinidcreateupdatebodyxml
1条回答
网友
1楼 · 发布于 2024-05-28 22:41:30

如果票证中只有一组“通信”和“正文”,则可以链接“查找”命令:

update = soup.find('correspondence').find('body')

否则,您必须使用find_all(Beauty Soup 4)或findAll(Beauty Soup 3)进行迭代:

correspondences = soup.find_all("correspondence")
for correspondence in correspondences:
    updates = correspondence.find_all("body")
    for update in updates:
    .....

相关问题 更多 >

    热门问题