Python có thể cạo dữ liệu từ trang web không?

Bài viết này thảo luận về các bước liên quan đến việc quét web bằng cách triển khai khung Web Scraping của Python có tên là Beautiful Soup. Các bước liên quan đến quét web

  1. Gửi yêu cầu HTTP tới URL của trang web bạn muốn truy cập. Máy chủ phản hồi yêu cầu bằng cách trả lại nội dung HTML của trang web. Đối với tác vụ này, chúng tôi sẽ sử dụng thư viện HTTP của bên thứ ba cho các yêu cầu python
  2. Khi chúng tôi đã truy cập nội dung HTML, chúng tôi còn lại nhiệm vụ phân tích dữ liệu. Vì hầu hết dữ liệu HTML được lồng vào nhau nên chúng tôi không thể trích xuất dữ liệu đơn giản thông qua xử lý chuỗi. Một người cần một trình phân tích cú pháp có thể tạo cấu trúc lồng/cây của dữ liệu HTML. Có nhiều thư viện trình phân tích cú pháp HTML nhưng thư viện tiên tiến nhất là html5lib
  3. Bây giờ, tất cả những gì chúng ta cần làm là điều hướng và tìm kiếm cây phân tích cú pháp mà chúng ta đã tạo. e. cây ngang. Đối với tác vụ này, chúng tôi sẽ sử dụng một thư viện python của bên thứ ba khác, Beautiful Soup. Nó là một thư viện Python để lấy dữ liệu ra khỏi các tệp HTML và XML

Bước 1. Cài đặt các thư viện bên thứ ba cần thiết

  • Cách dễ nhất để cài đặt các thư viện bên ngoài trong python là sử dụng pip. pip là một hệ thống quản lý gói được sử dụng để cài đặt và quản lý các gói phần mềm được viết bằng Python. Tất cả những gì bạn cần làm là
pip install requests
pip install html5lib
pip install bs4
  • Một cách khác là tải xuống thủ công từ các liên kết này
    • yêu cầu
    • html5lib
    • soup4

Bước 2. Truy cập nội dung HTML từ trang web

con trăn




import requests

URL

soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
1

soup = BeautifulSoup(r.content, 'html5lib')
2
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
4

soup = BeautifulSoup(r.content, 'html5lib')
5_______1_______6

Hãy để chúng tôi cố gắng hiểu đoạn mã này

  • Trước hết nhập thư viện yêu cầu
  • Sau đó, chỉ định URL của trang web bạn muốn cạo
  • Gửi yêu cầu HTTP tới URL đã chỉ định và lưu phản hồi từ máy chủ trong một đối tượng phản hồi có tên r
  • Bây giờ, như in r. nội dung để lấy nội dung HTML thô của trang web. Nó thuộc loại 'chuỗi'

Ghi chú. Đôi khi bạn có thể gặp lỗi “Không được chấp nhận”, vì vậy hãy thử thêm tác nhân người dùng trình duyệt như bên dưới. Tìm tác nhân người dùng của bạn dựa trên thiết bị và trình duyệt từ đây https. //deviceatlas. com/blog/list-of-user-agent-strings

Python3




soup = BeautifulSoup(r.content, 'html5lib')
7
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
9
table = soup.find('div', attrs = {'id':'all_quotes'}) 
0
table = soup.find('div', attrs = {'id':'all_quotes'}) 
1
table = soup.find('div', attrs = {'id':'all_quotes'}) 
2
table = soup.find('div', attrs = {'id':'all_quotes'}) 
3

table = soup.find('div', attrs = {'id':'all_quotes'}) 
4

soup = BeautifulSoup(r.content, 'html5lib')
2
soup = BeautifulSoup(r.content, 'html5lib')
0
table = soup.find('div', attrs = {'id':'all_quotes'}) 
7
soup = BeautifulSoup(r.content, 'html5lib')
0_______11_______9
soup = BeautifulSoup(r.content, 'html5lib')
0
for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
1

soup = BeautifulSoup(r.content, 'html5lib')
5_______1_______6

Bước 3. Phân tích cú pháp nội dung HTML

con trăn




for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
4

import requests

for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
7
for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
8import
quote['theme'] = row.h5.text
0

quote['theme'] = row.h5.text
1

URL

soup = BeautifulSoup(r.content, 'html5lib')
0
quote['theme'] = row.h5.text
4

soup = BeautifulSoup(r.content, 'html5lib')
2
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
4

quote['theme'] = row.h5.text
1

quote['theme'] = row.h5.text
9
soup = BeautifulSoup(r.content, 'html5lib')
0
quote['url'] = row.a['href']
1
quote['url'] = row.a['href']
2
quote['url'] = row.a['href']
3
quote['url'] = row.a['href']
4

soup = BeautifulSoup(r.content, 'html5lib')
5_______38_______6

Một điều thực sự hay về thư viện BeautifulSoup là nó được xây dựng dựa trên các thư viện phân tích cú pháp HTML như html5lib, lxml, html. trình phân tích cú pháp, v.v. Vì vậy, có thể tạo đồng thời đối tượng BeautifulSoup và chỉ định thư viện trình phân tích cú pháp. Trong ví dụ trên,

soup = BeautifulSoup(r.content, 'html5lib')

Chúng tôi tạo một đối tượng BeautifulSoup bằng cách chuyển hai đối số

  • r. nội dung. Đó là nội dung HTML thô
  • html5lib. Chỉ định trình phân tích cú pháp HTML mà chúng tôi muốn sử dụng

bây giờ súp. prettify() được in ra, nó cung cấp biểu diễn trực quan của cây phân tích cú pháp được tạo từ nội dung HTML thô. Bước 4. Tìm kiếm và điều hướng qua cây phân tích Bây giờ, chúng tôi muốn trích xuất một số dữ liệu hữu ích từ nội dung HTML. Đối tượng soup chứa tất cả dữ liệu trong cấu trúc lồng nhau có thể được trích xuất theo chương trình. Trong ví dụ của chúng tôi, chúng tôi đang cạo một trang web bao gồm một số trích dẫn. Vì vậy, chúng tôi muốn tạo một chương trình để lưu các trích dẫn đó (và tất cả thông tin liên quan về chúng).  

con trăn




quote['url'] = row.a['href']
7

quote['url'] = row.a['href']
8

import requests

for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
7
for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
8import
quote['theme'] = row.h5.text
0

import

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
6

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

URL

soup = BeautifulSoup(r.content, 'html5lib')
0
quote['theme'] = row.h5.text
4

soup = BeautifulSoup(r.content, 'html5lib')
2
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
4

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

quote['theme'] = row.h5.text
9
soup = BeautifulSoup(r.content, 'html5lib')
0
quote['url'] = row.a['href']
1
quote['url'] = row.a['href']
2
quote['url'] = row.a['href']
3

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

requests1

soup = BeautifulSoup(r.content, 'html5lib')
0requests3requests4

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

requests6_______1_______0 requests8requests9URL0

soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
9URL3
table = soup.find('div', attrs = {'id':'all_quotes'}) 
1URL5URL6

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

URL8 URL9

soup = BeautifulSoup(r.content, 'html5lib')
00
soup = BeautifulSoup(r.content, 'html5lib')
01requests9
soup = BeautifulSoup(r.content, 'html5lib')
03

soup = BeautifulSoup(r.content, 'html5lib')
04_______1_______05
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
9_______1_______08
table = soup.find('div', attrs = {'id':'all_quotes'}) 
1
soup = BeautifulSoup(r.content, 'html5lib')
10
soup = BeautifulSoup(r.content, 'html5lib')
11

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______13
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
15

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______17
soup = BeautifulSoup(r.content, 'html5lib')
18
soup = BeautifulSoup(r.content, 'html5lib')
19
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
21

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______17
soup = BeautifulSoup(r.content, 'html5lib')
24
soup = BeautifulSoup(r.content, 'html5lib')
19
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
27
soup = BeautifulSoup(r.content, 'html5lib')
28
soup = BeautifulSoup(r.content, 'html5lib')
19

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______17
soup = BeautifulSoup(r.content, 'html5lib')
32
soup = BeautifulSoup(r.content, 'html5lib')
19
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
35
soup = BeautifulSoup(r.content, 'html5lib')
36
soup = BeautifulSoup(r.content, 'html5lib')
19

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______17
soup = BeautifulSoup(r.content, 'html5lib')
40
soup = BeautifulSoup(r.content, 'html5lib')
19
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
35
soup = BeautifulSoup(r.content, 'html5lib')
44
soup = BeautifulSoup(r.content, 'html5lib')
45
soup = BeautifulSoup(r.content, 'html5lib')
46
soup = BeautifulSoup(r.content, 'html5lib')
47
soup = BeautifulSoup(r.content, 'html5lib')
48
soup = BeautifulSoup(r.content, 'html5lib')
19

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______17
soup = BeautifulSoup(r.content, 'html5lib')
52
soup = BeautifulSoup(r.content, 'html5lib')
19
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
35
soup = BeautifulSoup(r.content, 'html5lib')
44
soup = BeautifulSoup(r.content, 'html5lib')
45
soup = BeautifulSoup(r.content, 'html5lib')
46
soup = BeautifulSoup(r.content, 'html5lib')
47
soup = BeautifulSoup(r.content, 'html5lib')
60
soup = BeautifulSoup(r.content, 'html5lib')
19

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______63

filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
7

soup = BeautifulSoup(r.content, 'html5lib')
65
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
67

soup = BeautifulSoup(r.content, 'html5lib')
68
soup = BeautifulSoup(r.content, 'html5lib')
69
soup = BeautifulSoup(r.content, 'html5lib')
70
soup = BeautifulSoup(r.content, 'html5lib')
71
soup = BeautifulSoup(r.content, 'html5lib')
72
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
74

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______76
soup = BeautifulSoup(r.content, 'html5lib')
0
soup = BeautifulSoup(r.content, 'html5lib')
78
soup = BeautifulSoup(r.content, 'html5lib')
18
soup = BeautifulSoup(r.content, 'html5lib')
03
soup = BeautifulSoup(r.content, 'html5lib')
24
soup = BeautifulSoup(r.content, 'html5lib')
03
soup = BeautifulSoup(r.content, 'html5lib')
32
soup = BeautifulSoup(r.content, 'html5lib')
03
soup = BeautifulSoup(r.content, 'html5lib')
40
soup = BeautifulSoup(r.content, 'html5lib')
03
soup = BeautifulSoup(r.content, 'html5lib')
52
soup = BeautifulSoup(r.content, 'html5lib')
88

soup = BeautifulSoup(r.content, 'html5lib')
12_______1_______90

soup = BeautifulSoup(r.content, 'html5lib')
12_______174_______8
soup = BeautifulSoup(r.content, 'html5lib')
13
soup = BeautifulSoup(r.content, 'html5lib')
00
soup = BeautifulSoup(r.content, 'html5lib')
95

soup = BeautifulSoup(r.content, 'html5lib')
96
soup = BeautifulSoup(r.content, 'html5lib')
97

Trước khi tiếp tục, chúng tôi khuyên bạn nên xem qua nội dung HTML của trang web mà chúng tôi đã in bằng soup. prettify() và cố gắng tìm một mẫu hoặc cách để điều hướng đến các trích dẫn

  • Cần lưu ý rằng tất cả các trích dẫn đều nằm trong vùng chứa div có id là 'all_quotes'. Vì vậy, chúng tôi tìm thấy phần tử div đó (được gọi là bảng trong đoạn mã trên) bằng cách sử dụng phương thức find()
table = soup.find('div', attrs = {'id':'all_quotes'}) 
  • Đối số đầu tiên là thẻ HTML bạn muốn tìm kiếm và đối số thứ hai là phần tử loại từ điển để chỉ định các thuộc tính bổ sung được liên kết với thẻ đó. phương thức find() trả về phần tử khớp đầu tiên. Bạn có thể thử in bảng. prettify() để hiểu đoạn mã này làm gì
  • Bây giờ, trong phần tử bảng, người ta có thể nhận thấy rằng mỗi trích dẫn nằm trong một vùng chứa div có lớp là trích dẫn. Vì vậy, chúng tôi lặp qua từng vùng chứa div có lớp được trích dẫn. Ở đây, chúng ta sử dụng phương thức findAll() tương tự như phương thức find về đối số nhưng nó trả về một danh sách tất cả các phần tử phù hợp. Mỗi trích dẫn hiện được lặp lại bằng cách sử dụng một biến có tên là hàng. Đây là một nội dung HTML hàng mẫu để hiểu rõ hơn.
    Python có thể cạo dữ liệu từ trang web không?
    Bây giờ hãy xem xét đoạn mã này.
for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
  • Chúng tôi tạo một từ điển để lưu tất cả thông tin về một trích dẫn. Cấu trúc lồng nhau có thể được truy cập bằng ký hiệu dấu chấm. Để truy cập văn bản bên trong một phần tử HTML, chúng tôi sử dụng. chữ.  
quote['theme'] = row.h5.text
  • Chúng tôi có thể thêm, xóa, sửa đổi và truy cập các thuộc tính của thẻ. Điều này được thực hiện bằng cách coi thẻ như một từ điển
quote['url'] = row.a['href']
  • Cuối cùng, tất cả các dấu ngoặc kép được thêm vào danh sách được gọi là dấu ngoặc kép
  • Cuối cùng, chúng tôi muốn lưu tất cả dữ liệu của mình trong một số tệp CSV
filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)
  • Ở đây chúng tôi tạo một tệp CSV có tên làspired_quotes. csv và lưu tất cả các trích dẫn trong đó để sử dụng tiếp

Vì vậy, đây là một ví dụ đơn giản về cách tạo trình quét web bằng Python. Từ đây, bạn có thể cố gắng loại bỏ bất kỳ trang web nào khác mà bạn chọn. Trong trường hợp của bất kỳ truy vấn, gửi chúng dưới đây trong phần bình luận

Ghi chú. Web Scraping được coi là bất hợp pháp trong nhiều trường hợp. Nó cũng có thể khiến IP của bạn bị chặn vĩnh viễn bởi một trang web. Blog này được đóng góp bởi Nikhil Kumar. Nếu bạn thích GeeksforGeeks và muốn đóng góp, bạn cũng có thể viết một bài báo bằng cách sử dụng write. chuyên viên máy tính. org hoặc gửi bài viết của bạn tới review-team@geeksforgeeks. tổ chức. Xem bài viết của bạn xuất hiện trên trang chính của GeeksforGeeks và trợ giúp các Geeks khác. Vui lòng viết bình luận nếu bạn thấy bất cứ điều gì không chính xác hoặc bạn muốn chia sẻ thêm thông tin về chủ đề thảo luận ở trên

Python có thể cạo một trang web để lấy dữ liệu không?

Python được sử dụng cho nhiều thứ, từ phân tích dữ liệu đến lập trình máy chủ. Và một trường hợp sử dụng thú vị của Python là Quét web .

Có thể cạo dữ liệu từ các trang web không?

Việc thu thập dữ liệu trên web là hoàn toàn hợp pháp nếu bạn thu thập dữ liệu có sẵn công khai trên internet . Tuy nhiên, một số loại dữ liệu được bảo vệ theo quy định quốc tế, vì vậy hãy cẩn thận khi lấy dữ liệu cá nhân, tài sản trí tuệ hoặc dữ liệu bí mật.

Python có tốt hơn cho việc quét web không?

Python là lựa chọn tốt nhất cho bạn . Các thư viện như yêu cầu hoặc HTTPX giúp dễ dàng loại bỏ các trang web không yêu cầu JavaScript hoạt động chính xác. Python cung cấp rất nhiều ứng dụng khách HTTP dễ sử dụng. Và một khi bạn nhận được phản hồi, bạn cũng rất dễ dàng phân tích cú pháp HTML bằng BeautifulSoup chẳng hạn.