AttributeError: объект 'NoneType' не имеет атрибута 'text' (отлично находит другой тег в том же месте, но не может найти нужный тег) - PullRequest
0 голосов
/ 27 мая 2020

У меня есть файл xml, из которого я пытаюсь извлечь информацию. Ниже отрывок из файла

<?xml version="1.0" encoding="UTF-8"?>
<Terms>
    <Term>
        <Title>.177 (4.5mm) Airgun</Title>
        <Description>The standard airgun calibre for international target shooting.</Description>
        <RelatedTerms>
            <Term>
                <Title>Shooting sport equipment</Title>
                <Relationship>Narrower Term</Relationship>
            </Term>
        </RelatedTerms>
    </Term>
    <Term>
        <Title>.22</Title>
        <Description>A rimfire calibre, much used in target shooting and often synonymous with the term smallbore.</Description>
        <RelatedTerms>
            <Term>
                <Title>Shooting sport equipment</Title>
                <Relationship>Narrower Term</Relationship>
            </Term>
        </RelatedTerms>
    </Term>
    <Term>
        <Title>.22 Long Rifle</Title>
        <Description>The standard .22 rimfire cartridge for target rifle and pistol use.</Description>
        <RelatedTerms>
            <Term>
                <Title>Shooting sport equipment</Title>
                <Relationship>Narrower Term</Relationship>
            </Term>
        </RelatedTerms>
    </Term>
    <Term>
        <Title>.22 Short</Title>
        <Description>Used as a target shooting round for timed fire pistol competitions.</Description>
        <RelatedTerms>
            <Term>
                <Title>Shooting sport equipment</Title>
                <Relationship>Narrower Term</Relationship>
            </Term>
        </RelatedTerms>
    </Term>
</Terms>

Ниже приведен код, который я написал. Если я закомментирую "Title": rterm.find('Title').text,, весь код запускается и делает именно то, что ему нужно ... однако я получаю AttributeError: объект 'NoneType' не имеет атрибута 'text' , когда я пытаюсь запустить код с этой частью.

import json
import lxml
from bs4 import BeautifulSoup

xml_file = open('xml.xml', encoding='UTF-8') 
soup = BeautifulSoup(xml_file, 'lxml-xml', from_encoding='UTF-8')

Terms = soup.select('Terms > Term')  
jsonObj = {"thesaurus": []} 


for term in Terms: 
    termDetail = { 
        "Description": term.find('Description').text, 
        "Title": term.find('Title').text extracted 
    }
    RelatedTerms = term.select('RelatedTerms > Term')
    if RelatedTerms:
        termDetail["RelatedTerms"] = []
        for rterm in RelatedTerms:
            termDetail["RelatedTerms"].append({
                "Title": rterm.find('Title').text,
                "Relationship": rterm.find('Relationship').text
            })
    jsonObj["thesaurus"].append(termDetail)

with open(r'D:\UNI\data_science\fit5196\assessment_1b\json.dat', 'w') as json_file:
    json.dump(jsonObj, json_file, indent = 3, sort_keys = True ) 

Я действительно не знаю, почему возникает эта ошибка. в тексте есть текстовая информация, и он находит тег Relationship в порядке. Я в своем уме

Любые советы приветствуются

...