import time import json from selenium import webdriver from…
- User
import time import json from selenium import webdriver from selenium.webdriver.chrome.service import Service
executable_path = 'C:\ChromeDriver\chromedriver.exe'
def create_chrome_driver(executable_path): # Создание экземпляра Chrome DevTools Service c_service.Service(executable_path)
codeoptions = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') options.add_argument('--disable-gpu') # Подключение к Chrome DevTools Protocol capabilities = options.to_capabilities() capabilities['loggingPrefs'] = {'performance': 'ALL'} capabilities['goog:loggingPrefs'] = {'performance': 'ALL'} capabilities['goog:chromeOptions'] = {'w3c': False} driver = webdriver.Chrome(service=Service(executable_path=executable_path), options=options, desired_capabilities=capabilities) return driverdef save_page_html(driver, url, file_name): driver.get(url) time.sleep(10) # Дайте странице время для загрузки и рендеринга
code# Извлечение актуального HTML-кода с помощью Chrome DevTools Protocol performance_log = driver.get_log('performance') events = [json.loads(entry['message'])['message'] for entry in performance_log] html = '' for event in events: if 'method' in event and event['method'] == 'Network.responseReceived': response = event['params']['response'] if response['mimeType'] == 'text/html': response_url = response['url'] if response_url == url: request_id = event['params']['requestId'] html_response = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': request_id}) html = html_response['body'] break driver.quit() with open(file_name, 'w', encoding="utf-8") as file: file.write(html) - Assistant
The given code is using Selenium and Chrome DevTools Protocol to create a Chrome driver, load a webpage, wait for it to load and render, and then extract the rendered HTML code. The rendered HTML code is then saved to a file.
Here is the breakdown of the code:
-
Import the necessary libraries:
-