XML
Trong phần này, chúng ta sẽ parsing nội dung XML thành dữ liệu để xử lý. Để xử lý XML, ta sẽ sử dụng thư viện Beautifulsoup 4. Đây là một thư viện giúp việc triển khai việc parsing html, xml được nhanh chóng và tiện lợi.
Cài đặt
Bạn có thể tham khảo hướng dẫn cách cài đặt tại website: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup.
Trên MacOS, có thể cài bằng pip
như sau:
$ sudo pip install beautifulsoup4
Cài đặt lxml
parser
lxml
parserĐể parsing xml
từ beautifulsoup
, tao sử dụng bộ parser xml
có tên là lxml
. Xem hướng dẫn cài đặt tại
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing- a-parser
Trên MacOS, có thể cài bằng pip
như sau:
sudo pip install lxml
Ví dụ về parsing XML
from bs4 import BeautifulSoup as Soup
note = '''
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waff
les with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered
with strawberries and whipped cream</description>
<calories>900</calories>
</food>
</breakfast_menu>
'''
soup = Soup(note, 'xml')
foods = soup.findAll('food')
for x in foods:
print x.find('name').string, ': ', x.price.string
Kết quả:
Belgian Waffles : $5.95
Strawberry Belgian Waffles : $7.95
Đối tượng thuộc class Soup
(BeautifulSoup) sẽ giúp truy xuất các thành phần của file xml nhanh chóng và tiện lợi.
Trong ví dụ có một số cách truy xuất đến các phần tử như:
findAll()
Trả về mảng các thẻ có tên cần tìm.find()
Trả về phần tử đầu tiên có tên cần tìm.Truy xuất trực tiếp thông qua tên thẻ như
x.price.string.
Parsing HTML
Tương tự như xml
, BeautifulSoup
có thể parsing nội dung HTML thông qua hàm khởi tạo và chọn html ở tham số thứ 2.
...
soup = Soup(websitehtml, 'html')
Follower me
Facebook: https://www.facebook.com/lamsaodecode
Last updated
Was this helpful?