Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp

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 <module>
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é

Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp

  • Qua APT:
    Traceback (most recent call last):
      File "", line 1, in <module>
    ImportError: No module named bs4
    
    5
  • Qua PIP:
    Traceback (most recent call last):
      File "", line 1, in <module>
    ImportError: No module named bs4
    
    6
  • Qua EasyInstall:
    Traceback (most recent call last):
      File "", line 1, in <module>
    ImportError: No module named bs4
    
    7
  • 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:
      Traceback (most recent call last):
        File "", line 1, in <module>
      ImportError: No module named bs4
      
      8
    • Thay đổi thư mục hiện thời bằng lệnh:
      Traceback (most recent call last):
        File "", line 1, in <module>
      ImportError: No module named bs4
      
      9
    • Cài đặt:
      DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Documenttitle>
          <link rel="stylesheet" href="css.css" type="text/css">
      head>
      <body>
          
          <div class="items-list">
              <div class="item pull-right">
                  <p class="title">Item 001p>
                  <p class="price">Price: 01$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 002p>
                  <p class="price">Price: 02$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 003p>
                  <p class="price">Price: 03$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 004p>
                  <p class="price">Price: 04$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 005p>
                  <p class="price">Price: 05$p>
                  <p><a href="#">Buya>p>
              div>
          div>
          
      body>
      html>
      
      0

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>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
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 !
Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
!

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é !

Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
!

HTML5Lib

Để cài đặt HTML5Lib, bạn có thể làm theo 1 trong 3 cách:

  • Thông qua APT:
    • DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Documenttitle>
          <link rel="stylesheet" href="css.css" type="text/css">
      head>
      <body>
          
          <div class="items-list">
              <div class="item pull-right">
                  <p class="title">Item 001p>
                  <p class="price">Price: 01$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 002p>
                  <p class="price">Price: 02$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 003p>
                  <p class="price">Price: 03$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 004p>
                  <p class="price">Price: 04$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 005p>
                  <p class="price">Price: 05$p>
                  <p><a href="#">Buya>p>
              div>
          div>
          
      body>
      html>
      
      2
  • Thông qua PIP:
    • DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Documenttitle>
          <link rel="stylesheet" href="css.css" type="text/css">
      head>
      <body>
          
          <div class="items-list">
              <div class="item pull-right">
                  <p class="title">Item 001p>
                  <p class="price">Price: 01$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 002p>
                  <p class="price">Price: 02$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 003p>
                  <p class="price">Price: 03$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 004p>
                  <p class="price">Price: 04$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 005p>
                  <p class="price">Price: 05$p>
                  <p><a href="#">Buya>p>
              div>
          div>
          
      body>
      html>
      
      3
  • Thông qua EasyInstall
    • DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Documenttitle>
          <link rel="stylesheet" href="css.css" type="text/css">
      head>
      <body>
          
          <div class="items-list">
              <div class="item pull-right">
                  <p class="title">Item 001p>
                  <p class="price">Price: 01$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 002p>
                  <p class="price">Price: 02$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 003p>
                  <p class="price">Price: 03$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 004p>
                  <p class="price">Price: 04$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 005p>
                  <p class="price">Price: 05$p>
                  <p><a href="#">Buya>p>
              div>
          div>
          
      body>
      html>
      
      4

LXML

Để có thể cài đặt được LXML parser, bạn cần phải có 3 package sau:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
5,
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
6 và
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
7.

  • Cài đặt các required packages:
    • DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>Documenttitle>
          <link rel="stylesheet" href="css.css" type="text/css">
      head>
      <body>
          
          <div class="items-list">
              <div class="item pull-right">
                  <p class="title">Item 001p>
                  <p class="price">Price: 01$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 002p>
                  <p class="price">Price: 02$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 003p>
                  <p class="price">Price: 03$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 004p>
                  <p class="price">Price: 04$p>
                  <p><a href="#">Buya>p>
              div>
              <div class="item pull-right">
                  <p class="title">Item 005p>
                  <p class="price">Price: 05$p>
                  <p><a href="#">Buya>p>
              div>
          div>
          
      body>
      html>
      
      8
  • Cài đặt LXML parser:
    • Thông qua APT:
      • DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Documenttitle>
            <link rel="stylesheet" href="css.css" type="text/css">
        head>
        <body>
            
            <div class="items-list">
                <div class="item pull-right">
                    <p class="title">Item 001p>
                    <p class="price">Price: 01$p>
                    <p><a href="#">Buya>p>
                div>
                <div class="item pull-right">
                    <p class="title">Item 002p>
                    <p class="price">Price: 02$p>
                    <p><a href="#">Buya>p>
                div>
                <div class="item pull-right">
                    <p class="title">Item 003p>
                    <p class="price">Price: 03$p>
                    <p><a href="#">Buya>p>
                div>
                <div class="item pull-right">
                    <p class="title">Item 004p>
                    <p class="price">Price: 04$p>
                    <p><a href="#">Buya>p>
                div>
                <div class="item pull-right">
                    <p class="title">Item 005p>
                    <p class="price">Price: 05$p>
                    <p><a href="#">Buya>p>
                div>
            div>
            
        body>
        html>
        
        9
    • Thông qua PIP:
      • from bs4 import BeautifulSoup
        
        from_file_handle = BeautifulSoup(open('/tmp/bs4.html'))
        from_string = BeautifulSoup('data')
        
        0
    • Thông qua EasyInstall
      • from bs4 import BeautifulSoup
        
        from_file_handle = BeautifulSoup(open('/tmp/bs4.html'))
        from_string = BeautifulSoup('data')
        
        1

LXML

  • Để có thể cài đặt được LXML parser, bạn cần phải có 3 package sau:
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Documenttitle>
        <link rel="stylesheet" href="css.css" type="text/css">
    head>
    <body>
        
        <div class="items-list">
            <div class="item pull-right">
                <p class="title">Item 001p>
                <p class="price">Price: 01$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 002p>
                <p class="price">Price: 02$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 003p>
                <p class="price">Price: 03$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 004p>
                <p class="price">Price: 04$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 005p>
                <p class="price">Price: 05$p>
                <p><a href="#">Buya>p>
            div>
        div>
        
    body>
    html>
    
    5,
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Documenttitle>
        <link rel="stylesheet" href="css.css" type="text/css">
    head>
    <body>
        
        <div class="items-list">
            <div class="item pull-right">
                <p class="title">Item 001p>
                <p class="price">Price: 01$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 002p>
                <p class="price">Price: 02$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 003p>
                <p class="price">Price: 03$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 004p>
                <p class="price">Price: 04$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 005p>
                <p class="price">Price: 05$p>
                <p><a href="#">Buya>p>
            div>
        div>
        
    body>
    html>
    
    6 và
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Documenttitle>
        <link rel="stylesheet" href="css.css" type="text/css">
    head>
    <body>
        
        <div class="items-list">
            <div class="item pull-right">
                <p class="title">Item 001p>
                <p class="price">Price: 01$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 002p>
                <p class="price">Price: 02$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 003p>
                <p class="price">Price: 03$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 004p>
                <p class="price">Price: 04$p>
                <p><a href="#">Buya>p>
            div>
            <div class="item pull-right">
                <p class="title">Item 005p>
                <p class="price">Price: 05$p>
                <p><a href="#">Buya>p>
            div>
        div>
        
    body>
    html>
    
    7.
    • from bs4 import BeautifulSoup
      
      from_file_handle = BeautifulSoup(open('/tmp/bs4.html'))
      from_string = BeautifulSoup('data')
      
      2
  • Cài đặt các required packages:
    • from bs4 import BeautifulSoup
      
      from_file_handle = BeautifulSoup(open('/tmp/bs4.html'))
      from_string = BeautifulSoup('data')
      
      3
  • Cài đặt LXML parser:
    • Thông qua EasyInstall:
  • HTML5Lib
    • from bs4 import BeautifulSoup
      
      from_file_handle = BeautifulSoup(open('/tmp/bs4.html'))
      from_string = BeautifulSoup('data')
      
      6

Cách sử dụng các parser

Python html.parser

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>

LXML HTML parser

LXML XLM parser

Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
). Để 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>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
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ỉ
Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
?

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')
5

Chuẩ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

Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
! 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
Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
!

#!/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>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <link rel="stylesheet" href="css.css" type="text/css">
head>
<body>
    
    <div class="items-list">
        <div class="item pull-right">
            <p class="title">Item 001p>
            <p class="price">Price: 01$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 002p>
            <p class="price">Price: 02$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 003p>
            <p class="price">Price: 03$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 004p>
            <p class="price">Price: 04$p>
            <p><a href="#">Buya>p>
        div>
        <div class="item pull-right">
            <p class="title">Item 005p>
            <p class="price">Price: 05$p>
            <p><a href="#">Buya>p>
        div>
    div>
    
body>
html>
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ỉ ?
Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
!

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.

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)
<class 'bs4.element.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é !
Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp

(Pdb) title_tag.name = 'blockquote'
(Pdb) title_tag
<blockquote>Document</blockquote>

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();
8

Traceback (most recent call last):
  File "", line 1, in <module>
ImportError: No module named bs4
0

Bạ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 <module>
ImportError: No module named bs4
1

Bạ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 <module>
ImportError: No module named bs4
2

NavigableString

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)
<class 'bs4.element.Tag'>
(Pdb)
7

Traceback (most recent call last):
  File "", line 1, in <module>
ImportError: No module named bs4
3

Bạ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)
<class 'bs4.element.Tag'>
(Pdb)
8:

Traceback (most recent call last):
  File "", line 1, in <module>
ImportError: No module named bs4
4

Bà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é !

Hướng dẫn install beautifulsoup python - cài đặt python xinh đẹp
!