Beautiful Soup 4
Mục đích: Parse HTML, XML và Website scraping: Parse HTML, XML và Website scraping
Bạn muốn parse HTML, XML hay đơn giản là muốn scraping dữ liệu từ một website nào đó với ngôn ngữ Python? Trên Viblo cũng có một số bài của Anh Tranngoc về Scraping và Crawling dữ liệu từ một website nào đó với module Scrapy như: Kỹ thuật scraping và crawling Web nâng cao với Scrapy và SQLAlchemy hay Scraping và crawling Web với Scrapy và SQLAlchemy. Nay mình cũng xin phép giới thiệu một module cũng có thể scraping dữ liệu giống Scrapy nhưng nó nhẹ và đơn giản hơn cho những yêu cầu không đòi hỏi sự phức tạp như Scrapy, đó là Beautiful Soup. Chúng ta cùng đi tìm hiểu nó nhé!Anh Tranngoc về Scraping và Crawling dữ liệu từ một website nào đó với module Scrapy như: Kỹ thuật scraping và crawling Web nâng cao với Scrapy và SQLAlchemy hay Scraping và crawling Web với Scrapy và SQLAlchemy. Nay mình cũng xin phép giới thiệu một module cũng có thể scraping dữ liệu giống Scrapy nhưng nó nhẹ và đơn giản hơn cho những yêu cầu không đòi hỏi sự phức tạp như Scrapy, đó là Beautiful Soup. Chúng ta cùng đi tìm hiểu nó nhé!
Cài đặt
Trước tiên, chúng ta có thể kiểm tra xem trên máy của mình đã cài module này chưa hoặc nếu đã cài rồi, chúng ta xem mình đã ở phiên bản mới nhất chưa bằng 1 đoạn code ngắn trên terminal như sau:
python -c "import bs4; print[bs4.__version__];"
Sau khi thử đoạn code trên, nếu máy bạn đã cài rồi thì nó sẽ xuất hiện phiên bản của module BeautifulSoup. Còn không, bạn sẽ nhận được một lỗi như sau:
Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
Để cài Beautiful Soup 4, bạn có bốn cách là thông qua APT, PIP, EasyInstall hoặc thông qua source. Mình sẽ đưa ra cả bốn cách cài để bạn có thể lựa chọn cho phù hợp với sở thích của mình nhé
- Qua APT:
5Traceback [most recent call last]: File "", line 1, in ImportError: No module named bs4
- Qua PIP:
6Traceback [most recent call last]: File "", line 1, in ImportError: No module named bs4
- Qua EasyInstall:
7Traceback [most recent call last]: File "", line 1, in ImportError: No module named bs4
- Qua source:
- Vào trang download của Beautiful Soup tại đây rồi download phiên bản mà bạn muốn sử dụng.tại đây rồi download phiên bản mà bạn muốn sử dụng.
- Xả nén source bằng lệnh:
8Traceback [most recent call last]: File "", line 1, in ImportError: No module named bs4
- Thay đổi thư mục hiện thời bằng lệnh:
9Traceback [most recent call last]: File "", line 1, in ImportError: No module named bs4
- Cài đặt:
0DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
Nếu tất cả cách trên đều không thể cài đặt được, thì bạn vẫn có thể sử dụng nó bằng cách copy thư mục
DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
1 ở phần cài đặt bằng source vào thư mục source code của bạn rồi sử dụng như bình thường !Cài đặt parser
Beautiful Soup hỗ trợ thư viện HTML parser mặc định của Python và một số thư viện của bên thứ ba. Ví dụ như lxml parse hoặc html5lib parser. Mình sẽ hướng dẫn các bạn cài đặt cả 2 thư viện này nhé !
HTML5Lib
Để cài đặt HTML5Lib, bạn có thể làm theo 1 trong 3 cách:
- Thông qua APT:
2DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
- Thông qua PIP:
3DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
- Thông qua EasyInstall
4DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
LXML
Để có thể cài đặt được LXML parser, bạn cần phải có 3 package sau:
DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
5, DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
6 và DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
7.- Cài đặt các required packages:
8DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
- Cài đặt LXML parser:
- Thông qua APT:
9DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
- Thông qua PIP:
0from bs4 import BeautifulSoup from_file_handle = BeautifulSoup[open['/tmp/bs4.html']] from_string = BeautifulSoup['data']
- Thông qua EasyInstall
1from bs4 import BeautifulSoup from_file_handle = BeautifulSoup[open['/tmp/bs4.html']] from_string = BeautifulSoup['data']
- Thông qua APT:
LXML
- Để có thể cài đặt được LXML parser, bạn cần phải có 3 package sau:
5,DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
6 vàDOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
7.DOCTYPE html> Document Item 001 Price: 01$ Buy Item 002 Price: 02$ Buy Item 003 Price: 03$ Buy Item 004 Price: 04$ Buy Item 005 Price: 05$ Buy
2from bs4 import BeautifulSoup from_file_handle = BeautifulSoup[open['/tmp/bs4.html']] from_string = BeautifulSoup['data']
- Cài đặt các required packages:
3from bs4 import BeautifulSoup from_file_handle = BeautifulSoup[open['/tmp/bs4.html']] from_string = BeautifulSoup['data']
- Cài đặt LXML parser:
- Thông qua EasyInstall:
- HTML5Lib
6from bs4 import BeautifulSoup from_file_handle = BeautifulSoup[open['/tmp/bs4.html']] from_string = BeautifulSoup['data']
Cách sử dụng các parser
Python html.parser
DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
LXML HTML parser
LXML XLM parser
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 từ thư viện DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
1 rồi truyền file handle hoặc một chuỗi HTML [XML] vào constructor của from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 là có thể sử dụng được ngay. Xem ra món này nấu khá đơn giản đấy nhỉ from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
4 hoặc from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
5Chuẩn bị nguyên liệupdb [Python Debugger] để tiện cho việc debug code của chúng ta trên terminal. Nếu có thể, mình sẽ giới thiệu module pdb này trong bài viết tiếp theo của series PyMOTM này
#!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
Để thử Beautiful Soup, chúng ta sẽ tạo một file HTML với tên
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
7 trong thư mục from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
8 với nội dung như sau:Making the soup
Sau khi đã có đầy đủ nguyên liệu và dụng cụ rồi, chúng ta cùng nhau đi chế biến món soup nhé ]. Để parser một tài liệu, bạn chỉ cần import
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 từ thư viện DOCTYPE html>
Document
Item 001
Price: 01$
Buy
Item 002
Price: 02$
Buy
Item 003
Price: 03$
Buy
Item 004
Price: 04$
Buy
Item 005
Price: 05$
Buy
1 rồi truyền file handle hoặc một chuỗi HTML [XML] vào constructor của from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 là có thể sử dụng được ngay. Xem ra món này nấu khá đơn giản đấy nhỉ ?Ở from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 constructor, nếu bạn không truyền tên của parser mà bạn muốn sử dụng ở tham số thứ 2 thì mặc định nó sẽ sử dụng parser tốt nhất đang có sẵn trên hệ thống của bạn.
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
OK, bây giờ chúng ta sẽ đi vào chi tiết 1 chút về Beautiful Soup nhé. Trước khi đi vào chi tiết, chúng ta sẽ tạo 1 file code python đơn giản là đọc dữ liệu từ file
from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
7 mà chúng ta đã chuẩn bị từ trước để sử dụng nhé. Trong file code này, mình có sử dụng module pdb [Python Debugger] để tiện cho việc debug code của chúng ta trên terminal. Nếu có thể, mình sẽ giới thiệu module pdb này trong bài viết tiếp theo của series PyMOTM này ! Còn việc sử dụng parser nào thì tùy bạn quyết định nhé. Mình sẽ dùng HTML5Lib ![Pdb] title_tag = html_dom.find['title']
[Pdb] type[title_tag]
[Pdb]
Let's go [gogo]!
Các loại object của Beautiful Soup
[Pdb] title_tag.name
u'title'
Beautiful Soup sẽ chuyển đổi tài liệu HTML sang Python tree object. Nhưng bạn chỉ cần quan tâm 4 loại object là:
#!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
4, #!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
5, from bs4 import BeautifulSoup
from_file_handle = BeautifulSoup[open['/tmp/bs4.html']]
from_string = BeautifulSoup['data']
9 và #!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
7 thôi nhé ![Pdb] title_tag.name = 'blockquote'
[Pdb] title_tag
Document
Tag
Là một HTML [XML] tag
[Pdb] link_tag = html_dom.find['link']
[Pdb] link_tag['rel']
[u'stylesheet']
Name
[Pdb] link_tag.attrs
{u'href': u'css.css', u'type': u'text/css', u'rel': [u'stylesheet']}
Tên của tag. Bạn có thể lấy ra bằng cách sử dụng
#!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
8Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
0Bạn cũng có thể thay đổi tên của tag bằng cách gán cho nó 1 cái tên
Attributes
Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
1Bạn cũng có thể thêm/sửa/xóa một giá trị trong danh sách các giá trị của attribute đó:
Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
2NavigableString
Là nội dung text của tag đó.
#!/usr/bin/env python
from bs4 import BeautifulSoup
import pdb
html_dom = BeautifulSoup[open['/tmp/bs4.html'], 'html5lib']
# Dừng lại để chúng ta debug
pdb.set_trace[];
5 giống như một Python Unicode string, ngoại trừ việc nó hỗ trợ bạn một số tính năng như duyệt và tìm kiếm [sẽ được giới thiệu ở bài tiếp theo]. Bạn cũng có thể convert nó sang kiểu Unicode string bằng function [Pdb] title_tag = html_dom.find['title']
[Pdb] type[title_tag]
[Pdb]
7Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
3Bạn không thể sửa nội dung văn bản của 1 tag bằng cách trực tiếp, nhưng có thể thay thế nó thông qua function
[Pdb] title_tag = html_dom.find['title']
[Pdb] type[title_tag]
[Pdb]
8:Traceback [most recent call last]:
File "", line 1, in
ImportError: No module named bs4
4Bài viết cũng đã khá dài rồi mà chúng ta mới chỉ đi chưa được một nửa của Beautiful Soup, nên mình xin phép tạm dừng tại đây nhé. Phần 2 mình sẽ giới thiệu về việc duyệt và tìm kiếm nhé !