Hướng dẫn how do you parse an html response in python? - làm thế nào để bạn phân tích cú pháp một phản hồi html trong python?

Mã nguồn: lib/html/Parser.py Lib/html/parser.py


Mô-đun này xác định một lớp

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 đóng vai trò là cơ sở để phân tích các tệp văn bản được định dạng bằng HTML (Ngôn ngữ đánh dấu siêu văn bản) và XHTML.

classhtml.parser.htmlparser (*, convert_charrefs = true) ¶html.parser.HTMLParser(*, convert_charrefs=True)

Tạo một thể hiện phân tích cú pháp có thể phân tích đánh dấu không hợp lệ.

Nếu convert_charrefs là

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1 (mặc định), tất cả các tham chiếu ký tự (ngoại trừ các tài liệu trong ____ 12/________ 13 phần tử) sẽ tự động được chuyển đổi thành các ký tự unicode tương ứng.

Một ví dụ

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 được cho dữ liệu HTML và các phương thức xử lý gọi khi các thẻ bắt đầu, thẻ kết thúc, văn bản, nhận xét và các yếu tố đánh dấu khác gặp phải. Người dùng nên phân lớp
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 và ghi đè các phương thức của mình để thực hiện hành vi mong muốn.

Trình phân tích cú pháp này không kiểm tra xem các thẻ kết thúc có khớp thẻ bắt đầu hay gọi trình xử lý thẻ cuối cho các phần tử được đóng hoàn toàn bằng cách đóng một phần tử bên ngoài.

Đã thay đổi trong phiên bản 3.4: Convert_charrefs đối số từ khóa được thêm vào.convert_charrefs keyword argument added.

Đã thay đổi trong phiên bản 3.5: Giá trị mặc định cho đối số Convert_charrefs hiện là

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1.The default value for argument convert_charrefs is now
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1.

Ví dụ Ứng dụng phân tích cú pháp HTML

Ví dụ cơ bản, dưới đây là trình phân tích cú pháp HTML đơn giản sử dụng lớp

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 để in ra thẻ bắt đầu, thẻ cuối và dữ liệu khi chúng gặp phải:

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h2>Parse me!</h2></body></html>')

Đầu ra sau đó sẽ là:

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html

Encountered a start tag: html Encountered a start tag: head Encountered a start tag: title Encountered some data : Test Encountered an end tag : title Encountered an end tag : head Encountered a start tag: body Encountered a start tag: h2 Encountered some data : Parse me! Encountered an end tag : h2 Encountered an end tag : body Encountered an end tag : html 0 Phương pháp ¶

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 Các trường hợp có các phương pháp sau:

Htmlparser.feed (dữ liệu) ¶feed(data)

Cho ăn một số văn bản cho trình phân tích cú pháp. Nó được xử lý trong chừng mực vì nó bao gồm các yếu tố hoàn chỉnh; Dữ liệu không đầy đủ được đệm cho đến khi nhiều dữ liệu được cung cấp hoặc

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
0 được gọi. Dữ liệu phải là
from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
1.

Htmlparser.close ()close()

Xử lý lực của tất cả dữ liệu được đệm như thể nó được theo sau bởi một dấu cuối cùng. Phương pháp này có thể được xác định lại bởi một lớp dẫn xuất để xác định xử lý bổ sung ở cuối đầu vào, nhưng phiên bản được xác định lại phải luôn gọi phương thức lớp cơ sở ____1010

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
0.

Htmlparser.reset ()reset()

Đặt lại trường hợp. Mất tất cả dữ liệu chưa qua xử lý. Điều này được gọi là ngầm vào thời điểm khởi tạo.

Htmlparser.getpos ()getpos()

Trả về số dòng hiện tại và bù.

Htmlparser.get_starttag_text () ¶get_starttag_text()

Trả về văn bản của thẻ bắt đầu được mở gần đây nhất. Điều này thường không cần thiết để xử lý có cấu trúc, nhưng có thể hữu ích trong việc xử lý HTML, khi được triển khai hoặc để tạo lại đầu vào với những thay đổi tối thiểu (có thể bảo tồn được khoảng trắng giữa các thuộc tính, v.v.).

Các phương pháp sau được gọi là khi các phần tử dữ liệu hoặc đánh dấu gặp phải và chúng có nghĩa là được ghi đè trong một lớp con. Việc triển khai lớp cơ sở không làm gì cả (ngoại trừ

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
4):

Htmlparser.handle_starttag (tag, attrs) ¶handle_starttag(tag, attrs)

Phương thức này được gọi để xử lý thẻ bắt đầu của một phần tử (ví dụ:

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
5).

Đối số thẻ là tên của thẻ được chuyển đổi thành chữ thường. Đối số attrs là một danh sách các cặp

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
6 chứa các thuộc tính được tìm thấy bên trong dấu ngoặc ____ ____27. Tên sẽ được dịch thành chữ thường và trích dẫn trong giá trị đã được xóa, và các tài liệu tham khảo ký tự và thực thể đã được thay thế.

Chẳng hạn, đối với thẻ

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
8, phương pháp này sẽ được gọi là
from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()
9.

Tất cả các tham chiếu thực thể từ

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
0 được thay thế trong các giá trị thuộc tính.

Htmlparser.handle_endtag (tag) ¶handle_endtag(tag)

Phương thức này được gọi để xử lý thẻ cuối của một phần tử (ví dụ:

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
1).

Đối số thẻ là tên của thẻ được chuyển đổi thành chữ thường.

Htmlparser.handle_startendtag (tag, attrs) ¶handle_startendtag(tag, attrs)

Tương tự như

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
2, nhưng được gọi khi trình phân tích cú pháp gặp một thẻ trống kiểu XHTML (
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
3). Phương pháp này có thể được ghi đè bởi các lớp con yêu cầu thông tin từ vựng cụ thể này; Việc triển khai mặc định chỉ đơn giản gọi
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
2 và
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
5.

Htmlparser.handle_data (dữ liệu) ¶handle_data(data)

Phương pháp này được gọi để xử lý dữ liệu tùy ý (ví dụ: các nút văn bản và nội dung của

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
6 và
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
7).

Htmlparser.handle_entityref (tên) ¶handle_entityref(name)

Phương pháp này được gọi để xử lý một tham chiếu ký tự được đặt tên của mẫu

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
8 (ví dụ:
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
9), trong đó tên là một tham chiếu thực thể chung (ví dụ:
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
0). Phương pháp này không bao giờ được gọi nếu Convert_charrefs là
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1.

Htmlparser.handle_charref (tên) ¶handle_charref(name)

Phương pháp này được gọi là xử lý các tham chiếu ký tự số thập phân và thập lục phân của mẫu

>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
2 và
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
3. Ví dụ, tương đương thập phân cho
>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
9 là
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
5, trong khi thập lục phân là
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
6; Trong trường hợp này, phương thức sẽ nhận được
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
7 hoặc
>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2
8. Phương pháp này không bao giờ được gọi nếu Convert_charrefs là
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1.

Htmlparser.handle_comment (dữ liệu) ¶handle_comment(data)

Phương pháp này được gọi là khi gặp bình luận (ví dụ:

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
0).

Ví dụ: nhận xét

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
1 sẽ khiến phương thức này được gọi với đối số
>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
2.

Nội dung của Internet Explorer Nhận xét có điều kiện (Condcoms) cũng sẽ được gửi đến phương thức này, vì vậy, đối với

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
3, phương pháp này sẽ nhận được
>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
4.

Htmlparser.handle_decl (khai báo) ¶handle_decl(decl)

Phương pháp này được gọi để xử lý khai báo HTML DocType (ví dụ:

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
5).

Tham số DEC sẽ là toàn bộ nội dung của khai báo bên trong đánh dấu

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
6 (ví dụ:
>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
7).

Htmlparser.handle_pi (dữ liệu) ¶handle_pi(data)

Phương thức được gọi khi gặp phải hướng dẫn xử lý. Tham số dữ liệu sẽ chứa toàn bộ hướng dẫn xử lý. Ví dụ: đối với hướng dẫn xử lý

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
8, phương pháp này sẽ được gọi là
>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script
9. Nó được dự định sẽ được ghi đè bởi một lớp dẫn xuất; Việc thực hiện lớp cơ sở không làm gì cả.

Ghi chú

Lớp

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
0 sử dụng các quy tắc cú pháp SGML để xử lý hướng dẫn. Một hướng dẫn xử lý XHTML bằng cách sử dụng Trailing
>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
1 sẽ khiến
>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
1 được đưa vào dữ liệu.

Htmlparser.unknown_decl (dữ liệu) ¶unknown_decl(data)

Phương pháp này được gọi là khi một tuyên bố không được công nhận được đọc bởi trình phân tích cú pháp.

Tham số dữ liệu sẽ là toàn bộ nội dung của khai báo bên trong đánh dấu

>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
3. Đôi khi rất hữu ích khi được ghi đè bởi một lớp dẫn xuất. Việc thực hiện lớp cơ sở không làm gì cả.

Ví dụ;

Lớp sau đây thực hiện trình phân tích cú pháp sẽ được sử dụng để minh họa thêm các ví dụ:

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()

Phân tích cú pháp do DocType:

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"

Phân tích một phần tử với một vài thuộc tính và một tiêu đề:

>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h2>Python</h2>')
Start tag: h2
Data     : Python
End tag  : h2

Nội dung của các yếu tố

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
2 và
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
3 được trả về, mà không cần phân tích cú pháp thêm:

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script

Nhận xét phân tích cú pháp:

>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]

Phân tích phân tích các tham chiếu ký tự được đặt tên và số và chuyển đổi chúng sang chính xác (lưu ý: 3 tài liệu tham khảo này đều tương đương với

>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
6):

>>> parser.feed('&gt;&#62;&#x3E;')
Named ent: >
Num ent  : >
Num ent  : >

Cho ăn các khối không đầy đủ cho

>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
7 hoạt động, nhưng
>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]
8 có thể được gọi nhiều lần (trừ khi convert_charrefs được đặt thành
Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h2
Encountered some data  : Parse me!
Encountered an end tag : h2
Encountered an end tag : body
Encountered an end tag : html
1):

>>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
...     parser.feed(chunk)
...
Start tag: span
Data     : buff
Data     : ered
Data     : text
End tag  : span

Phân tích cú pháp HTML không hợp lệ (ví dụ: các thuộc tính chưa được trích xuất) cũng hoạt động:

>>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
     attr: ('class', 'link')
     attr: ('href', '#main')
Data     : tag soup
End tag  : p
End tag  : a

Làm cách nào để phân tích HTML trong Python?

Example..
từ HTML. Nhập phân tích cú pháp Htmlparser ..
Trình phân tích cú pháp lớp (HTMLPARSER):.
# Phương thức để nối thẻ bắt đầu vào danh sách start_tags ..
DEF Tay cầm_starttag (self, Tag, attrs):.
Global start_tags ..
start_tags. Phụ lục (thẻ).
# Phương thức nối thẻ kết thúc vào danh sách end_tags ..
DEF Tay cầm_endtag (self, tag):.

Gói Python nào bạn có thể sử dụng để phân tích HTML?

Súp đẹp (BS4) là một thư viện Python được sử dụng để phân tích thông tin ra khỏi các tệp HTML hoặc XML.Nó phân tích đầu vào của nó vào một đối tượng mà bạn có thể chạy nhiều tìm kiếm.Để bắt đầu phân tích tệp HTML, hãy nhập thư viện súp đẹp và tạo một đối tượng súp đẹp như trong ví dụ mã sau. is a Python library that is used to parse information out of HTML or XML files. It parses its input into an object on which you can run a variety of searches. To start parsing an HTML file, import the Beautiful Soup library and create a Beautiful Soup object as shown in the following code example.

Làm thế nào để trình phân tích cú pháp HTML hoạt động Python?

Trình phân tích cú pháp HTML, như tên cho thấy, chỉ cần phân tích cú pháp nội dung HTML/XHTML của trang web và cung cấp thông tin chúng tôi đang tìm kiếm.Đây là một lớp được xác định với các phương pháp khác nhau có thể được ghi đè cho phù hợp với yêu cầu của chúng tôi.Lưu ý rằng để sử dụng trình phân tích cú pháp HTML, trang web phải được tìm nạp.parses a web page's HTML/XHTML content and provides the information we are looking for. This is a class that is defined with various methods that can be overridden to suit our requirements. Note that to use HTML Parser, the web page must be fetched.

Làm thế nào để bạn phân tích HTML?

Phân tích cú pháp HTML liên quan đến việc xây dựng mã thông báo và xây dựng cây.Mã thông báo HTML bao gồm các thẻ bắt đầu và kết thúc, cũng như tên và giá trị thuộc tính.Nếu tài liệu được hình thành tốt, phân tích cú pháp thì đơn giản và nhanh hơn.Trình phân tích cú pháp phân tích cú pháp đầu vào vào tài liệu, xây dựng cây tài liệu.tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.