Hướng dẫn how to download data from website using python - cách tải dữ liệu từ trang web bằng python


Python cung cấp các mô -đun khác nhau như urllib, yêu cầu vv để tải xuống các tệp từ web. Tôi sẽ sử dụng thư viện yêu cầu của Python để tải xuống các tệp một cách hiệu quả từ các URL.

Hãy bắt đầu xem xét thủ tục từng bước để tải xuống các tệp bằng URL bằng thư viện yêu cầu -

1. Nhập mô -đun

import requests

2. Nhận liên kết hoặc URL

url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

3. Lưu nội dung với tên.

open('facebook.ico', 'wb').write(r.content)

Lưu tệp dưới dạng Facebook.ICO.

Thí dụ

import requests


url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

open('facebook.ico', 'wb').write(r.content)

Kết quả

Hướng dẫn how to download data from website using python - cách tải dữ liệu từ trang web bằng python

Chúng ta có thể thấy tệp được tải xuống (biểu tượng) trong thư mục làm việc hiện tại của chúng tôi.

Nhưng chúng ta có thể cần tải xuống các loại tệp khác nhau như hình ảnh, văn bản, video, vv từ web. Vì vậy, trước tiên, hãy để có được loại dữ liệu mà URL đang liên kết đến−

>>> r = requests.get(url, allow_redirects=True)
>>> print(r.headers.get('content-type'))
image/png

Tuy nhiên, có một cách thông minh hơn, liên quan đến việc tìm kiếm các tiêu đề của một URL trước khi thực sự tải xuống nó. Điều này cho phép chúng tôi bỏ qua việc tải xuống các tệp mà người sói có nghĩa là sẽ được tải xuống.

>>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
False
>>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
True

Để hạn chế tải xuống theo kích thước tệp, chúng tôi có thể lấy FileZie từ tiêu đề độ dài nội dung và sau đó thực hiện theo yêu cầu của chúng tôi.

contentLength = header.get('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb approx
return False

Nhận tên tệp từ một url

Để có được tên tệp, chúng ta có thể phân tích URL. Dưới đây là một thói quen mẫu lấy chuỗi cuối cùng sau khi chao đảo (/).

url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
if url.find('/'):
print(url.rsplit('/', 1)[1]

Trên đây sẽ cung cấp tên tệp của URL. Tuy nhiên, có nhiều trường hợp thông tin tệp không có trong URL chẳng hạn - http://url.com/doad. Trong trường hợp như vậy, chúng ta cần phải có tiêu đề xử lý nội dung, chứa thông tin tên tệp.

import requests
import re

def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0]


url = 'http://google.com/favicon.ico'
r = requests.get(url, allow_redirects=True)
filename = getFilename_fromCd(r.headers.get('content-disposition'))
open(filename, 'wb').write(r.content)

Mã phân tích URL trên kết hợp với chương trình trên sẽ cung cấp cho bạn tên tệp từ tiêu đề xử lý nội dung hầu hết thời gian.

Hướng dẫn how to download data from website using python - cách tải dữ liệu từ trang web bằng python

Cập nhật vào ngày 30 tháng 3 năm 2019 22:30:26

  • Câu hỏi và câu trả lời liên quan
  • Tải xuống tệp bằng trình kết nối SAP .NET
  • Làm thế nào các tệp được trích xuất từ ​​một tệp tar bằng Python?
  • Đổi tên nhiều tệp bằng Python
  • Sử dụng dịch vụ web SAP từ tệp WSDL
  • Web Scraping bằng Python và Scracy?
  • Python thực hiện quét web bằng LXML
  • Làm thế nào để sao chép các tệp từ thư mục này sang thư mục khác bằng Python?
  • Làm thế nào để sao chép các tệp từ máy chủ này sang máy chủ khác bằng Python?
  • Làm thế nào để chuyển đổi các tệp PDF sang các tệp Excel bằng Python?
  • Làm thế nào để sao chép một số tệp nhất định từ thư mục này sang thư mục khác bằng Python?
  • Thực hiện quét web bằng LXML trong Python?
  • HTML5 có cho phép bạn tương tác với các tệp máy khách cục bộ từ trong trình duyệt web không?
  • Tạo các tệp và thư mục tạm thời bằng cách sử dụng Python
  • Làm thế nào để xóa các tệp hoán đổi bằng Python?
  • Cách tạo các tệp PowerPoint bằng Python

Yêu cầu là một thư viện HTTP đa năng trong Python với các ứng dụng khác nhau. Một trong những ứng dụng của nó là tải xuống một tệp từ Web bằng tệp URL.installation: Trước hết, bạn sẽ cần tải xuống thư viện yêu cầu. Bạn có thể trực tiếp cài đặt nó bằng PIP bằng cách nhập lệnh sau:
Installation: First of all, you would need to download the requests library. You can directly install it using pip by typing following command:

pip install requests

Hoặc tải xuống trực tiếp từ đây và cài đặt thủ công.

Tải tập tin

Món mã nhỏ được viết ở trên sẽ tải xuống hình ảnh sau từ web. Bây giờ hãy kiểm tra thư mục cục bộ của bạn (thư mục nơi tập lệnh này cư trú) và bạn sẽ tìm thấy hình ảnh này:

Tất cả những gì chúng ta cần là URL của nguồn hình ảnh. (Bạn có thể lấy URL của nguồn hình ảnh bằng cách nhấp chuột phải vào hình ảnh và chọn tùy chọn xem hình ảnh.)

Tải xuống các tập tin lớn

Nội dung phản hồi HTTP (R.Content) không là gì ngoài một chuỗi đang lưu trữ dữ liệu tệp. Vì vậy, nó đã giành chiến thắng để lưu tất cả dữ liệu trong một chuỗi trong trường hợp các tệp lớn. Để khắc phục vấn đề này, chúng tôi thực hiện một số thay đổi cho chương trình của mình:r.content) is nothing but a string which is storing the file data. So, it won’t be possible to save all the data in a single string in case of large files. To overcome this problem, we do some changes to our program:

  • Vì tất cả dữ liệu tệp có thể được lưu trữ bởi một chuỗi duy nhất, chúng tôi sử dụng phương thức r.iter_content để tải dữ liệu theo khối, chỉ định kích thước chunk.r.iter_content method to load data in chunks, specifying the chunk size.
  • url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    0

    Đặt tham số luồng thành true sẽ chỉ khiến việc tải xuống các tiêu đề phản hồi và kết nối vẫn mở. Điều này tránh đọc tất cả nội dung cùng một lúc vào bộ nhớ cho các phản hồi lớn. Một khối cố định sẽ được tải mỗi lần trong khi r.iter_content được lặp lại.stream parameter to True will cause the download of response headers only and the connection remains open. This avoids reading the content all at once into memory for large responses. A fixed chunk will be loaded each time while r.iter_content is iterated.

    Đây là một ví dụ:

    Tải xuống video

    Trong ví dụ này, chúng tôi quan tâm đến việc tải xuống tất cả các bài giảng video có sẵn trên trang web này. Tất cả các tài liệu lưu trữ của bài giảng này có sẵn ở đây. Vì vậy, trước tiên chúng tôi xóa trang web để trích xuất tất cả các liên kết video và sau đó tải xuống từng video.

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    1
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    2

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    3
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    4
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    1
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    6

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    7
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    8

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    open('facebook.ico', 'wb').write(r.content)
    0
    open('facebook.ico', 'wb').write(r.content)
    1
    open('facebook.ico', 'wb').write(r.content)
    2

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    open('facebook.ico', 'wb').write(r.content)
    4
    open('facebook.ico', 'wb').write(r.content)
    1
    open('facebook.ico', 'wb').write(r.content)
    6
    open('facebook.ico', 'wb').write(r.content)
    7
    open('facebook.ico', 'wb').write(r.content)
    8

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    03021
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    2
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    3
    open('facebook.ico', 'wb').write(r.content)
    8

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    6
    open('facebook.ico', 'wb').write(r.content)
    1
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    8
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    9
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    0
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    1__

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    >>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
    False
    >>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
    True
    4
    >>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
    False
    >>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
    True
    5

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    7
    >>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
    False
    >>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
    True
    7

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    3
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    4
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    5
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    2

    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    3
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    4
    open('facebook.ico', 'wb').write(r.content)
    1
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    6
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    7
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    8
    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    3

    Các

    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    3
    open('facebook.ico', 'wb').write(r.content)
    0
    open('facebook.ico', 'wb').write(r.content)
    1
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    1
    open('facebook.ico', 'wb').write(r.content)
    1
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    3
    open('facebook.ico', 'wb').write(r.content)
    8

    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    3
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    6
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    7
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    8
    import requests
    import re
    
    def getFilename_fromCd(cd):
    """
    Get filename from content-disposition
    """
    if not cd:
    return None
    fname = re.findall('filename=(.+)', cd)
    if len(fname) == 0:
    return None
    return fname[0]
    
    
    url = 'http://google.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    filename = getFilename_fromCd(r.headers.get('content-disposition'))
    open(filename, 'wb').write(r.content)
    9
    pip install requests
    0

    pip install requests
    1
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    3
    pip install requests
    3
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    5

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    01
    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    7
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    03

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    04
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    05

    contentLength = header.get('content-length', None)
    if contentLength and contentLength > 2e8: # 200 mb approx
    return False
    3
    url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
    if url.find('/'):
    print(url.rsplit('/', 1)[1]
    3
    url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
    if url.find('/'):
    print(url.rsplit('/', 1)[1]
    4
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    09
    url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
    if url.find('/'):
    print(url.rsplit('/', 1)[1]
    6
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    11

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
    if url.find('/'):
    print(url.rsplit('/', 1)[1]
    3
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    14
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    15
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    16

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    >>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
    False
    >>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
    True
    4

    >>> r = requests.get(url, allow_redirects=True)
    >>> print(r.headers.get('content-type'))
    image/png
    7
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    20
    open('facebook.ico', 'wb').write(r.content)
    1
    open('facebook.ico', 'wb').write(r.content)
    1
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    23
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    24

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    import requests
    
    
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    
    open('facebook.ico', 'wb').write(r.content)
    6
    open('facebook.ico', 'wb').write(r.content)
    1
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    28

    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    9
    url = 'https://www.facebook.com/favicon.ico'
    r = requests.get(url, allow_redirects=True)
    30

    Ưu điểm của việc sử dụng thư viện yêu cầu để tải xuống các tệp web là:

    • Người ta có thể dễ dàng tải xuống các thư mục web bằng cách lặp lại đệ quy thông qua trang web!
    • Đây là một phương pháp độc lập với trình duyệt và nhanh hơn nhiều!
    • Người ta có thể chỉ cần xóa một trang web để lấy tất cả các URL tệp trên trang web và do đó, tải xuống tất cả các tệp trong một lệnh-

      Thực hiện quét web trong Python với BeautifulSoup

    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 viết bằng Write.GeekSforGeek.org hoặc gửi bài viết của bạn. Xem bài viết của bạn xuất hiện trên trang chính của GeekSforGeek và giúp các chuyên viên máy tính khác.

    Vui lòng viết nhận xét nếu bạn tìm 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ủ đề được thảo luận ở trên.


    Làm cách nào để tải xuống bộ dữ liệu từ một trang web trong Python?

    Để trích xuất dữ liệu bằng cách sử dụng máy quét web với Python, bạn cần làm theo các bước cơ bản sau:..
    Tìm URL mà bạn muốn cạo ..
    Kiểm tra trang ..
    Tìm dữ liệu bạn muốn trích xuất ..
    Viết mã ..
    Chạy mã và trích xuất dữ liệu ..
    Lưu trữ dữ liệu theo định dạng cần thiết ..

    Python có thể trích xuất dữ liệu từ trang web không?

    Các cách khác nhau để trích xuất dữ liệu từ trang web, chúng ta có thể sử dụng nó thông qua mô -đun RE của Python. Nó cũng được gọi là các mẫu re hoặc regexes hoặc regex. Với sự trợ giúp của các biểu thức thông thường, chúng tôi có thể chỉ định một số quy tắc cho tập hợp các chuỗi có thể mà chúng tôi muốn khớp từ dữ liệu.We can use it through re module of Python. It is also called RE or regexes or regex patterns. With the help of regular expressions, we can specify some rules for the possible set of strings we want to match from the data.

    Làm cách nào để tải xuống dữ liệu từ một trang web?

    Có khoảng 5 bước như dưới đây:..
    Kiểm tra trang web HTML mà bạn muốn bò ..
    Truy cập URL của trang web bằng mã và tải xuống tất cả các nội dung HTML trên trang ..
    Định dạng nội dung đã tải xuống thành một định dạng có thể đọc được ..
    Trích xuất thông tin hữu ích và lưu nó vào một định dạng có cấu trúc ..

    Làm cách nào để tải xuống tệp zip từ một trang web bằng Python?

    Nếu bạn chỉ muốn lưu tệp từ URL bạn có thể làm: Urllib.Request.urlretrieve (URL, FileName).urllib. request. urlretrieve(url, filename) .