HTML — XML: как решить ошибку синтаксического анализа (текст)

#python #xml #jupyter

#питон #xml #jupyter

Вопрос:

Недавно я начал изучать веб-доступ, сервис и XML из Jupyter Notebook, и я столкнулся с обратной трассировкой, которая мне непонятна, как ее решить. Может ли кто-нибудь дать мне направление, чтобы найти решение?

Вот код:

 import re
import string
from bs4 import BeautifulSoup as bs
import xml.etree.ElementTree as ET

data = """
<html>
    <head>
        <title>HTML read as XML</title>
    </head>
    <body>
        <header>
            <h1>HTML file</h1>
        </header>
            <person>
                <name> Madderman </name>
                <phone type='local'> 
                            088 043 04 30
                </phone>
            </person>
            <table>
                <tr>
                    <th>Some stuff</th>
                    <td>Value/ Element</td>                   
                </tr>
                <tr>
                    <th><Some stuff with other stuff</th>
                    <td>Value /element</td>
                </tr>
            </table>
        <script></script>
    </body>
</html> """

check = ET.fromstring(data)  # This code import the data by directly reading from a string which is the root element of the parsed tree

print('Name', check.find('name').text) <br>
print('Phone', check.find('phone').text)
 

Вот трассировка:
Файл «/home/jupyterlab/conda/envs/python/lib/python3.6/xml/etree/ElementTree.py «, строка 1314, в XML parser.feed(текст)

Заранее спасибо!

Комментарии:

1. @ Luke Woodward Спасибо за форматирование!

Ответ №1:

Ваш XML-документ недействителен.

<th><Some stuff with other stuff</th>

Посмотрите < , что у вас есть перед словом Some


Вы должны использовать правильный xpath

 import xml.etree.ElementTree as ET

data = """
<html>
    <head>
        <title>HTML read as XML</title>
    </head>
    <body>
        <header>
            <h1>HTML file</h1>
        </header>
            <person>
                <name> Madderman </name>
                <phone type='local'> 
                            088 043 04 30
                </phone>
            </person>
            <table>
                <tr>
                    <th>Some stuff</th>
                    <td>Value/ Element</td>                   
                </tr>
                <tr>
                    <th>Some stuff with other stuff</th>
                    <td>Value /element</td>
                </tr>
            </table>
        <script></script>
    </body>
</html> """

check = ET.fromstring( data) 


print('Name', check.find('.//name').text)
print('Phone', check.find('.//phone').text)
 

выходной сигнал

 Name  Madderman 
Phone  
                            088 043 04 30
 

Комментарии:

1. Спасибо, что обратили на это внимание. Но сейчас я перехожу к обратной трассировке: AttributeError Traceback (последний последний вызов) <ipython-input-38-10c3f0d9091c> в <модуле> 37 38 check = ET.fromstring(данные) —> 39 print(‘Имя’, check.find(‘имя’).текст) 40 печать (‘Email’, проверка.найти(’email’).получить(‘скрыть’)) 41 Ошибка атрибута: объект ‘NoneType’ не имеет атрибута ‘text’