Cách trích xuất dữ liệu từ URL trong Python

Khi thực hiện phân tích nội dung trên quy mô lớn, bạn sẽ cần tự động trích xuất nội dung văn bản từ các trang web

Trong bài viết này, bạn sẽ tìm hiểu cách trích xuất nội dung văn bản từ một trang web và nhiều trang web bằng Python

!pip install beautifulsoup4 !pip install numpy !pip install requests !pip install spacy !pip install trafilatura

NB. Nếu bạn đang viết điều này trong một tệp python tiêu chuẩn, bạn sẽ không cần bao gồm. Biểu tượng. Điều này chỉ vì hướng dẫn này được viết trong Jupyter Notebook

Đầu tiên chúng ta sẽ chia vấn đề thành nhiều giai đoạn

  1. Trích xuất tất cả nội dung HTML bằng cách sử dụng các yêu cầu vào từ điển python
  2. Chuyển từng trang HTML đơn lẻ tới Trafilatura để phân tích nội dung văn bản
  3. Thêm xử lý lỗi và ngoại lệ để nếu Trafilatura không thành công, chúng tôi vẫn có thể trích xuất nội dung, mặc dù với cách tiếp cận kém chính xác hơn
from bs4 import BeautifulSoup import json import numpy as np import requests from requests.models import MissingSchema import spacy import trafilatura

Thu thập nội dung HTML từ trang web

urls = ['//understandingdata.com/', '//sempioneer.com/',]data = {} for url in urls: # 1. Obtain the response: resp = requests.get(url) # 2. If the response content is 200 - Status Ok, Save The HTML Content: if resp.status_code == 200: data[url] = resp.text

Trích xuất văn bản từ một trang web

Sau khi thu thập tất cả các yêu cầu có status_code là 200, giờ đây chúng tôi có thể áp dụng một số nỗ lực để trích xuất nội dung văn bản từ mọi yêu cầu

Trước tiên, chúng tôi sẽ cố gắng sử dụng trafilatura, tuy nhiên nếu thư viện này không thể trích xuất văn bản thì chúng tôi sẽ sử dụng BeautifulSoup4 làm phương án dự phòng

def beautifulsoup_extract_text_fallback(response_content): ''' This is a fallback function, so that we can always return a value for text content. Even for when both Trafilatura and BeautifulSoup are unable to extract the text from a single URL. ''' # Create the beautifulsoup object: soup = BeautifulSoup(response_content, 'html.parser') # Finding the text: text = soup.find_all(text=True) # Remove unwanted tag elements: cleaned_text = '' blacklist = [ '[document]', 'noscript', 'header', 'html', 'meta', 'head', 'input', 'script', 'style',] # Then we will loop over every item in the extract text and make sure that the beautifulsoup4 tag # is NOT in the blacklist for item in text: if item.parent.name not in blacklist: cleaned_text += '{} '.format(item) # Remove any tab separation and strip the text: cleaned_text = cleaned_text.replace('\t', '') return cleaned_text.strip() def extract_text_from_single_web_page(url): downloaded_url = trafilatura.fetch_url(url) try: a = trafilatura.extract(downloaded_url, json_output=True, with_metadata=True, include_comments = False, date_extraction_params={'extensive_search': True, 'original_date': True}) except AttributeError: a = trafilatura.extract(downloaded_url, json_output=True, with_metadata=True, date_extraction_params={'extensive_search': True, 'original_date': True}) if a: json_output = json.loads(a) return json_output['text'] else: try: resp = requests.get(url) # We will only extract the text from successful requests: if resp.status_code == 200: return beautifulsoup_extract_text_fallback(resp.content) else: # This line will handle for any failures in both the Trafilature and BeautifulSoup4 functions: return np.nan # Handling for any URLs that don't have the correct protocol except MissingSchema: return np.nansingle_url = '//understandingdata.com/' text = extract_text_from_single_web_page(url=single_url) print(text)

Trích xuất văn bản từ nhiều trang web

Hãy sử dụng khả năng hiểu danh sách với chức năng văn bản single_extract của chúng tôi để dễ dàng trích xuất văn bản từ nhiều trang web

urls = urls + ['fake_url'] text_content = [extract_text_from_single_web_page(url) for url in urls] print(text_content[1]) print(text_content[-1:])

Lưu ý cách chúng tôi đảm bảo rằng bất kỳ URL nào không thành công đều có thể dễ dàng bị xóa khi chúng tôi trả về np. nan (không phải số).

Làm sạch văn bản thô của chúng tôi từ nhiều trang web

Sau khi bạn đã trích xuất thành công các tài liệu văn bản thô, hãy xóa mọi trang web không thành công

________số 8

Ngoài ra, bạn có thể muốn làm sạch văn bản để phân tích thêm. Ví dụ: mã hóa nội dung văn bản cho phép bạn phân tích cảm xúc, cấu trúc câu, các yếu tố phụ thuộc ngữ nghĩa và cả số lượng từ

nlp = spacy.load("en_core_web_sm")from bs4 import BeautifulSoup import json import numpy as np import requests from requests.models import MissingSchema import spacy import trafilatura0

Phần kết luận

Hy vọng rằng giờ đây bạn có thể dễ dàng trích xuất nội dung văn bản từ một hoặc nhiều url

Chúng tôi cũng đã bao gồm beautifulsoup như một chức năng dự phòng/dự phòng. Điều này đảm bảo rằng mã của chúng tôi ít dễ hỏng hơn và có thể chịu được các lỗi sau

Chủ đề