Python100個庫分享第37個—BeautifulSoup(爬蟲篇)

目錄

    • 專欄導讀
    • 📚 庫簡介
      • 🎯 主要特點
    • 🛠? 安裝方法
    • 🚀 快速入門
      • 基本使用流程
      • 解析器選擇
    • 🔍 核心功能詳解
      • 1. 基本查找方法
        • find() 和 find_all()
        • CSS選擇器
      • 2. 屬性操作
      • 3. 文本提取
    • 🕷? 實戰爬蟲案例
      • 案例1:爬取新聞標題和鏈接
      • 案例2:爬取商品信息
      • 案例3:爬取表格數據
    • 🛡? 高級技巧與最佳實踐
      • 1. 處理動態內容
      • 2. 數據清洗和驗證
      • 3. 處理編碼問題
      • 4. 并發爬取
    • ?? 注意事項與最佳實踐
      • 1. 遵守robots.txt
      • 2. 設置合理的延遲
      • 3. 錯誤處理和日志記錄
    • 🔧 常見問題解決
      • 1. 處理JavaScript渲染的頁面
      • 2. 處理反爬蟲機制
    • 📊 性能優化
      • 1. 內存優化
      • 2. 緩存機制
    • 🎯 總結
      • ? 優點
      • ?? 局限性
      • 🚀 最佳實踐建議

專欄導讀

  • 🌸 歡迎來到Python辦公自動化專欄—Python處理辦公問題,解放您的雙手

  • 🏳??🌈 博客主頁:請點擊——> 一晌小貪歡的博客主頁求關注

  • 👍 該系列文章專欄:請點擊——>Python辦公自動化專欄求訂閱

  • 🕷 此外還有爬蟲專欄:請點擊——>Python爬蟲基礎專欄求訂閱

  • 📕 此外還有python基礎專欄:請點擊——>Python基礎學習專欄求訂閱

  • 文章作者技術和水平有限,如果文中出現錯誤,希望大家能指正🙏

  • ?? 歡迎各位佬關注! ??

📚 庫簡介

  • BeautifulSoup是Python中最受歡迎的HTML和XML解析庫之一,專門用于網頁數據提取和網絡爬蟲開發。它提供了簡單易用的API來解析HTML/XML文檔,讓開發者能夠輕松地從網頁中提取所需的數據。

🎯 主要特點

  • 簡單易用:提供直觀的API,即使是初學者也能快速上手
  • 強大的解析能力:支持多種解析器(html.parser、lxml、html5lib等)
  • 靈活的查找方式:支持CSS選擇器、標簽名、屬性等多種查找方式
  • 容錯性強:能夠處理格式不規范的HTML文檔
  • 與requests完美配合:是網絡爬蟲開發的黃金組合

🛠? 安裝方法

# 基礎安裝
pip install beautifulsoup4# 推薦安裝(包含lxml解析器)
pip install beautifulsoup4 lxml# 完整安裝(包含所有解析器)
pip install beautifulsoup4 lxml html5lib

🚀 快速入門

基本使用流程

from bs4 import BeautifulSoup
import requests# 1. 獲取網頁內容
url = "https://example.com"
response = requests.get(url)
html_content = response.text# 2. 創建BeautifulSoup對象
soup = BeautifulSoup(html_content, 'html.parser')# 3. 解析和提取數據
title = soup.find('title').text
print(f"網頁標題: {title}")

解析器選擇

from bs4 import BeautifulSouphtml = "<html><head><title>測試頁面</title></head><body><p>Hello World</p></body></html>"# 不同解析器的使用
soup1 = BeautifulSoup(html, 'html.parser')    # Python內置解析器
soup2 = BeautifulSoup(html, 'lxml')           # lxml解析器(推薦)
soup3 = BeautifulSoup(html, 'html5lib')       # html5lib解析器

🔍 核心功能詳解

1. 基本查找方法

find() 和 find_all()
from bs4 import BeautifulSouphtml = """
<html>
<body><div class="container"><h1 id="title">主標題</h1><p class="content">第一段內容</p><p class="content">第二段內容</p><a href="https://example.com">鏈接1</a><a href="https://test.com">鏈接2</a></div>
</body>
</html>
"""soup = BeautifulSoup(html, 'html.parser')# find() - 查找第一個匹配的元素
first_p = soup.find('p')
print(f"第一個p標簽: {first_p.text}")# find_all() - 查找所有匹配的元素
all_p = soup.find_all('p')
for p in all_p:print(f"p標簽內容: {p.text}")# 根據屬性查找
title = soup.find('h1', id='title')
content_p = soup.find_all('p', class_='content')
CSS選擇器
# 使用CSS選擇器
soup = BeautifulSoup(html, 'html.parser')# select() - 返回列表
titles = soup.select('h1')
contents = soup.select('.content')
links = soup.select('a[href]')# select_one() - 返回第一個匹配元素
first_content = soup.select_one('.content')# 復雜選擇器
nested_elements = soup.select('div.container p.content')

2. 屬性操作

from bs4 import BeautifulSouphtml = '<a href="https://example.com" class="external" id="link1">示例鏈接</a>'
soup = BeautifulSoup(html, 'html.parser')link = soup.find('a')# 獲取屬性
href = link.get('href')
# 或者使用字典方式
href = link['href']# 獲取所有屬性
attrs = link.attrs
print(f"所有屬性: {attrs}")# 檢查屬性是否存在
if link.has_attr('class'):print(f"class屬性: {link['class']}")# 修改屬性
link['href'] = 'https://newurl.com'
link['target'] = '_blank'

3. 文本提取

from bs4 import BeautifulSouphtml = """
<div><h1>標題</h1><p>這是一段<strong>重要</strong>的文本</p><ul><li>項目1</li><li>項目2</li></ul>
</div>
"""soup = BeautifulSoup(html, 'html.parser')# 獲取文本內容
div = soup.find('div')# .text - 獲取所有文本(包括子元素)
all_text = div.text
print(f"所有文本: {all_text}")# .get_text() - 更靈活的文本提取
clean_text = div.get_text(separator=' ', strip=True)
print(f"清理后的文本: {clean_text}")# .string - 只有當元素只包含一個字符串時才返回
p = soup.find('p')
print(f"p標簽的string: {p.string}")  # None,因為包含子元素# .strings - 生成器,返回所有字符串
for string in div.strings:print(f"字符串: {repr(string)}")

🕷? 實戰爬蟲案例

案例1:爬取新聞標題和鏈接

import requests
from bs4 import BeautifulSoup
import timedef crawl_news():"""爬取新聞網站的標題和鏈接"""# 設置請求頭,模擬瀏覽器訪問headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}try:# 發送請求url = "https://news.example.com"  # 替換為實際的新聞網站response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()# 解析HTMLsoup = BeautifulSoup(response.text, 'html.parser')# 查找新聞標題(根據實際網站結構調整選擇器)news_items = soup.find_all('div', class_='news-item')news_list = []for item in news_items:title_element = item.find('h3') or item.find('h2')link_element = item.find('a')if title_element and link_element:title = title_element.get_text(strip=True)link = link_element.get('href')# 處理相對鏈接if link.startswith('/'):link = f"https://news.example.com{link}"news_list.append({'title': title,'link': link})return news_listexcept requests.RequestException as e:print(f"請求錯誤: {e}")return []# 使用示例
if __name__ == "__main__":news = crawl_news()for item in news[:5]:  # 顯示前5條新聞print(f"標題: {item['title']}")print(f"鏈接: {item['link']}")print("-" * 50)

案例2:爬取商品信息

import requests
from bs4 import BeautifulSoup
import json
import timeclass ProductCrawler:def __init__(self):self.session = requests.Session()self.session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'})def crawl_product_list(self, category_url):"""爬取商品列表頁面"""try:response = self.session.get(category_url, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')# 查找商品容器(根據實際網站調整)products = soup.find_all('div', class_='product-item')product_list = []for product in products:product_info = self.extract_product_info(product)if product_info:product_list.append(product_info)return product_listexcept Exception as e:print(f"爬取商品列表失敗: {e}")return []def extract_product_info(self, product_element):"""提取單個商品信息"""try:# 商品名稱name_element = product_element.find('h3', class_='product-name')name = name_element.get_text(strip=True) if name_element else "未知商品"# 價格price_element = product_element.find('span', class_='price')price = price_element.get_text(strip=True) if price_element else "價格未知"# 圖片img_element = product_element.find('img')image_url = img_element.get('src') if img_element else ""# 商品鏈接link_element = product_element.find('a')product_url = link_element.get('href') if link_element else ""# 評分rating_element = product_element.find('span', class_='rating')rating = rating_element.get_text(strip=True) if rating_element else "無評分"return {'name': name,'price': price,'image_url': image_url,'product_url': product_url,'rating': rating}except Exception as e:print(f"提取商品信息失敗: {e}")return Nonedef save_to_json(self, products, filename):"""保存數據到JSON文件"""try:with open(filename, 'w', encoding='utf-8') as f:json.dump(products, f, ensure_ascii=False, indent=2)print(f"數據已保存到 {filename}")except Exception as e:print(f"保存文件失敗: {e}")# 使用示例
if __name__ == "__main__":crawler = ProductCrawler()# 爬取商品信息products = crawler.crawl_product_list("https://shop.example.com/category/electronics")# 保存數據if products:crawler.save_to_json(products, "products.json")print(f"共爬取到 {len(products)} 個商品")

案例3:爬取表格數據

import requests
from bs4 import BeautifulSoup
import pandas as pddef crawl_table_data(url, table_selector=None):"""爬取網頁中的表格數據"""headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')# 查找表格if table_selector:table = soup.select_one(table_selector)else:table = soup.find('table')if not table:print("未找到表格")return None# 提取表頭headers_row = table.find('thead') or table.find('tr')headers = []if headers_row:for th in headers_row.find_all(['th', 'td']):headers.append(th.get_text(strip=True))# 提取數據行rows = []tbody = table.find('tbody')if tbody:data_rows = tbody.find_all('tr')else:data_rows = table.find_all('tr')[1:]  # 跳過表頭行for row in data_rows:cells = row.find_all(['td', 'th'])row_data = []for cell in cells:# 處理單元格內容cell_text = cell.get_text(strip=True)row_data.append(cell_text)if row_data:  # 只添加非空行rows.append(row_data)# 創建DataFrameif headers and rows:# 確保所有行的列數一致max_cols = max(len(headers), max(len(row) for row in rows) if rows else 0)# 補齊表頭while len(headers) < max_cols:headers.append(f"Column_{len(headers) + 1}")# 補齊數據行for row in rows:while len(row) < max_cols:row.append("")df = pd.DataFrame(rows, columns=headers[:max_cols])return dfreturn Noneexcept Exception as e:print(f"爬取表格數據失敗: {e}")return None# 使用示例
if __name__ == "__main__":# 爬取表格數據url = "https://example.com/data-table"df = crawl_table_data(url)if df is not None:print("表格數據預覽:")print(df.head())# 保存到CSVdf.to_csv("table_data.csv", index=False, encoding='utf-8-sig')print("數據已保存到 table_data.csv")

🛡? 高級技巧與最佳實踐

1. 處理動態內容

from bs4 import BeautifulSoup
import requests
import timedef crawl_with_retry(url, max_retries=3, delay=1):"""帶重試機制的爬取函數"""headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}for attempt in range(max_retries):try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()return response.textexcept requests.RequestException as e:print(f"第 {attempt + 1} 次嘗試失敗: {e}")if attempt < max_retries - 1:time.sleep(delay * (attempt + 1))  # 遞增延遲else:raisereturn None

2. 數據清洗和驗證

import re
from bs4 import BeautifulSoupclass DataCleaner:@staticmethoddef clean_text(text):"""清理文本數據"""if not text:return ""# 移除多余的空白字符text = re.sub(r'\s+', ' ', text.strip())# 移除特殊字符text = re.sub(r'[^\w\s\u4e00-\u9fff.,!?;:]', '', text)return text@staticmethoddef extract_price(price_text):"""提取價格數字"""if not price_text:return None# 使用正則表達式提取數字price_match = re.search(r'[\d,]+\.?\d*', price_text.replace(',', ''))if price_match:return float(price_match.group().replace(',', ''))return None@staticmethoddef validate_url(url):"""驗證URL格式"""url_pattern = re.compile(r'^https?://'  # http:// or https://r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...r'localhost|'  # localhost...r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ipr'(?::\d+)?'  # optional portr'(?:/?|[/?]\S+)$', re.IGNORECASE)return url_pattern.match(url) is not None# 使用示例
cleaner = DataCleaner()# 清理文本
dirty_text = "  這是一段   包含多余空格的\n\n文本  "
clean_text = cleaner.clean_text(dirty_text)
print(f"清理后的文本: '{clean_text}'")# 提取價格
price_text = "¥1,299.99"
price = cleaner.extract_price(price_text)
print(f"提取的價格: {price}")

3. 處理編碼問題

import requests
from bs4 import BeautifulSoup
import chardetdef smart_crawl(url):"""智能處理編碼的爬取函數"""headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}try:response = requests.get(url, headers=headers, timeout=10)response.raise_for_status()# 檢測編碼detected_encoding = chardet.detect(response.content)encoding = detected_encoding['encoding']print(f"檢測到的編碼: {encoding}")# 使用檢測到的編碼解碼if encoding:html_content = response.content.decode(encoding, errors='ignore')else:html_content = response.text# 創建BeautifulSoup對象soup = BeautifulSoup(html_content, 'html.parser')return soupexcept Exception as e:print(f"爬取失敗: {e}")return None

4. 并發爬取

import asyncio
import aiohttp
from bs4 import BeautifulSoup
import timeclass AsyncCrawler:def __init__(self, max_concurrent=5):self.max_concurrent = max_concurrentself.semaphore = asyncio.Semaphore(max_concurrent)async def fetch_page(self, session, url):"""異步獲取單個頁面"""async with self.semaphore:try:async with session.get(url, timeout=10) as response:if response.status == 200:html = await response.text()return url, htmlelse:print(f"HTTP {response.status}: {url}")return url, Noneexcept Exception as e:print(f"獲取頁面失敗 {url}: {e}")return url, Noneasync def crawl_multiple_pages(self, urls):"""并發爬取多個頁面"""headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}async with aiohttp.ClientSession(headers=headers) as session:tasks = [self.fetch_page(session, url) for url in urls]results = await asyncio.gather(*tasks)return resultsdef parse_pages(self, results):"""解析爬取結果"""parsed_data = []for url, html in results:if html:soup = BeautifulSoup(html, 'html.parser')# 提取數據(根據實際需求調整)title = soup.find('title')title_text = title.get_text(strip=True) if title else "無標題"parsed_data.append({'url': url,'title': title_text,'content_length': len(html)})return parsed_data# 使用示例
async def main():urls = ["https://example1.com","https://example2.com","https://example3.com",# 添加更多URL]crawler = AsyncCrawler(max_concurrent=3)start_time = time.time()results = await crawler.crawl_multiple_pages(urls)parsed_data = crawler.parse_pages(results)end_time = time.time()print(f"爬取完成,耗時: {end_time - start_time:.2f}秒")print(f"成功爬取: {len(parsed_data)} 個頁面")for data in parsed_data:print(f"URL: {data['url']}")print(f"標題: {data['title']}")print(f"內容長度: {data['content_length']}")print("-" * 50)# 運行異步爬蟲
if __name__ == "__main__":asyncio.run(main())

?? 注意事項與最佳實踐

1. 遵守robots.txt

import urllib.robotparserdef check_robots_txt(url, user_agent='*'):"""檢查robots.txt是否允許爬取"""try:rp = urllib.robotparser.RobotFileParser()rp.set_url(f"{url}/robots.txt")rp.read()return rp.can_fetch(user_agent, url)except:return True  # 如果無法獲取robots.txt,默認允許# 使用示例
url = "https://example.com/page"
if check_robots_txt(url):print("允許爬取")
else:print("robots.txt禁止爬取")

2. 設置合理的延遲

import time
import randomclass RateLimiter:def __init__(self, min_delay=1, max_delay=3):self.min_delay = min_delayself.max_delay = max_delayself.last_request_time = 0def wait(self):"""等待適當的時間間隔"""current_time = time.time()elapsed = current_time - self.last_request_timedelay = random.uniform(self.min_delay, self.max_delay)if elapsed < delay:sleep_time = delay - elapsedtime.sleep(sleep_time)self.last_request_time = time.time()# 使用示例
rate_limiter = RateLimiter(min_delay=1, max_delay=3)for url in urls:rate_limiter.wait()  # 等待# 執行爬取操作response = requests.get(url)

3. 錯誤處理和日志記錄

import logging
from datetime import datetime# 配置日志
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler('crawler.log', encoding='utf-8'),logging.StreamHandler()]
)logger = logging.getLogger(__name__)class SafeCrawler:def __init__(self):self.success_count = 0self.error_count = 0def crawl_with_logging(self, url):"""帶日志記錄的爬取函數"""try:logger.info(f"開始爬取: {url}")response = requests.get(url, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')self.success_count += 1logger.info(f"爬取成功: {url}")return soupexcept requests.exceptions.Timeout:self.error_count += 1logger.error(f"請求超時: {url}")except requests.exceptions.HTTPError as e:self.error_count += 1logger.error(f"HTTP錯誤 {e.response.status_code}: {url}")except Exception as e:self.error_count += 1logger.error(f"未知錯誤: {url} - {str(e)}")return Nonedef get_stats(self):"""獲取爬取統計信息"""total = self.success_count + self.error_countsuccess_rate = (self.success_count / total * 100) if total > 0 else 0return {'total': total,'success': self.success_count,'errors': self.error_count,'success_rate': f"{success_rate:.2f}%"}

🔧 常見問題解決

1. 處理JavaScript渲染的頁面

# 對于JavaScript渲染的頁面,BeautifulSoup無法直接處理
# 需要配合Selenium使用from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoupdef crawl_js_page(url):"""爬取JavaScript渲染的頁面"""# 配置Chrome選項chrome_options = Options()chrome_options.add_argument('--headless')  # 無頭模式chrome_options.add_argument('--no-sandbox')chrome_options.add_argument('--disable-dev-shm-usage')try:driver = webdriver.Chrome(options=chrome_options)driver.get(url)# 等待頁面加載time.sleep(3)# 獲取渲染后的HTMLhtml = driver.page_source# 使用BeautifulSoup解析soup = BeautifulSoup(html, 'html.parser')return soupfinally:driver.quit()

2. 處理反爬蟲機制

import random
import timeclass AntiAntiCrawler:def __init__(self):self.user_agents = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36']self.session = requests.Session()def get_random_headers(self):"""獲取隨機請求頭"""return {'User-Agent': random.choice(self.user_agents),'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3','Accept-Encoding': 'gzip, deflate','Connection': 'keep-alive',}def crawl_with_proxy(self, url, proxy=None):"""使用代理爬取"""headers = self.get_random_headers()proxies = {'http': proxy, 'https': proxy} if proxy else Nonetry:response = self.session.get(url, headers=headers, proxies=proxies,timeout=10)return response.textexcept Exception as e:print(f"爬取失敗: {e}")return None

📊 性能優化

1. 內存優化

from bs4 import BeautifulSoup
import gcdef memory_efficient_crawl(urls):"""內存高效的爬取方法"""for url in urls:try:response = requests.get(url, stream=True)# 分塊讀取大文件content = ""for chunk in response.iter_content(chunk_size=8192, decode_unicode=True):content += chunksoup = BeautifulSoup(content, 'html.parser')# 處理數據process_page(soup)# 清理內存del soupdel contentgc.collect()except Exception as e:print(f"處理 {url} 時出錯: {e}")def process_page(soup):"""處理頁面數據"""# 只提取需要的數據,避免保存整個soup對象title = soup.find('title')if title:print(f"標題: {title.get_text(strip=True)}")

2. 緩存機制

import pickle
import os
from datetime import datetime, timedeltaclass CrawlerCache:def __init__(self, cache_dir='cache', expire_hours=24):self.cache_dir = cache_dirself.expire_hours = expire_hoursif not os.path.exists(cache_dir):os.makedirs(cache_dir)def get_cache_path(self, url):"""獲取緩存文件路徑"""import hashliburl_hash = hashlib.md5(url.encode()).hexdigest()return os.path.join(self.cache_dir, f"{url_hash}.cache")def is_cache_valid(self, cache_path):"""檢查緩存是否有效"""if not os.path.exists(cache_path):return Falsecache_time = datetime.fromtimestamp(os.path.getmtime(cache_path))expire_time = datetime.now() - timedelta(hours=self.expire_hours)return cache_time > expire_timedef get_cached_content(self, url):"""獲取緩存內容"""cache_path = self.get_cache_path(url)if self.is_cache_valid(cache_path):try:with open(cache_path, 'rb') as f:return pickle.load(f)except:passreturn Nonedef save_to_cache(self, url, content):"""保存到緩存"""cache_path = self.get_cache_path(url)try:with open(cache_path, 'wb') as f:pickle.dump(content, f)except Exception as e:print(f"保存緩存失敗: {e}")# 使用示例
cache = CrawlerCache()def crawl_with_cache(url):"""帶緩存的爬取函數"""# 嘗試從緩存獲取cached_content = cache.get_cached_content(url)if cached_content:print(f"使用緩存: {url}")return BeautifulSoup(cached_content, 'html.parser')# 從網絡獲取try:response = requests.get(url, timeout=10)response.raise_for_status()# 保存到緩存cache.save_to_cache(url, response.text)return BeautifulSoup(response.text, 'html.parser')except Exception as e:print(f"爬取失敗: {e}")return None

🎯 總結

BeautifulSoup是Python爬蟲開發中不可或缺的工具,它的優勢在于:

? 優點

  • 簡單易學:API設計直觀,學習曲線平緩
  • 功能強大:支持多種查找方式和解析器
  • 容錯性好:能處理格式不規范的HTML
  • 文檔完善:官方文檔詳細,社區活躍

?? 局限性

  • 不支持JavaScript:無法處理動態渲染的內容
  • 性能相對較慢:相比lxml等純C庫性能較低
  • 內存占用:解析大文件時內存占用較高

🚀 最佳實踐建議

  1. 選擇合適的解析器:推薦使用lxml解析器
  2. 遵守網站規則:檢查robots.txt,設置合理延遲
  3. 錯誤處理:完善的異常處理和重試機制
  4. 數據清洗:對提取的數據進行驗證和清理
  5. 性能優化:使用緩存、并發等技術提高效率
  • BeautifulSoup配合requests庫,是Python爬蟲開發的經典組合,適合大多數網頁數據提取任務。掌握這個庫,將為你的數據采集工作提供強大的支持!

  • 希望對初學者有幫助;致力于辦公自動化的小小程序員一枚

  • 希望能得到大家的【??一個免費關注??】感謝!

  • 求個 🤞 關注 🤞 +?? 喜歡 ?? +👍 收藏 👍

  • 此外還有辦公自動化專欄,歡迎大家訂閱:Python辦公自動化專欄

  • 此外還有爬蟲專欄,歡迎大家訂閱:Python爬蟲基礎專欄

  • 此外還有Python基礎專欄,歡迎大家訂閱:Python基礎學習專欄

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/915535.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/915535.shtml
英文地址,請注明出處:http://en.pswp.cn/news/915535.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

石子入水波紋效果:頂點擾動著色器實現

水面波紋的真實模擬是計算機圖形學中一個經典且重要的課題,廣泛應用于游戲、影視和虛擬現實等領域。本文將從技術原理和實現細節出發,系統介紹如何利用**頂點擾動(Vertex Displacement)**技術,結合多種輔助方法,打造既真實又高效的水面波紋效果。 一、頂點擾動的核心思想…

【FFmpeg 快速入門】本地播放器 項目

目錄 &#x1f308;前言&#x1f308; &#x1f4c1; 整體架構 詳細流程 &#x1f4c1; 數據流向? &#x1f4c1; 隊列設計?編輯 &#x1f4c1; 線程設計 &#x1f4c1; 音視頻同步 &#x1f4c1; 音頻輸出設計 &#x1f4c1; 視頻輸出設計 &#x1f4c1; 總結 …

Maven dependencyManagement標簽 properties標簽

dependencyManagement標簽properties標簽

前端埋坑之element Ui 組件el-progress display:flex后不顯示進度條解決方案

項目適用場景&#xff1a; <divs style"display&#xff1a;flex"> <span>這里是進度條前標題說明</span> <el-progress :percentage"50"></el-progress> </div> 問題呈現&#xff1a; el-progress進度條沒啦&#xf…

嵌入式學習-土堆PyTorch(7)-day23

損失函數的調用import torch from torch import nn from torch.nn import L1Lossinputs torch.tensor([1.0,2.0,3.0]) target torch.tensor([1.0,2.0,5.0])inputs torch.reshape(inputs, (1, 1, 1, 3)) target torch.reshape(target, (1, 1, 1, 3)) #損失函數 loss L1Loss…

【2025最新】使用neo4j實現GraphRAG所需的向量檢索

學習筆記&#xff0c;比較混亂&#xff0c;介意慎點。 背景 在將UMLS或者LightRAG構造的數據庫存入neo4j之后&#xff0c;我開始將知識圖譜運用到實際場景的使用中、例如查詢、推理。然而&#xff0c;由于字符串匹配導致大量術語在檢索時出現缺失。導致檢索效果不佳。我們需要…

【AI深究】隨機森林(Random Forest)全網最詳細全流程詳解與案例(附Python代碼演示)|集成學習|數學原理、案例流程、代碼演示及結果解讀|參數與調優、工程啟示、單棵決策樹的對比、優缺點

大家好&#xff0c;我是愛醬。本篇將會系統地講解隨機森林&#xff08;Random Forest&#xff09;的原理、核心思想、數學表達、算法流程、代碼實現與工程應用。內容適合初學者和進階讀者&#xff0c;配合公式和可視化示例。 注&#xff1a;本文章含大量數學算式、詳細例子說明…

6.String、StringBuffer、StringBuilder區別及使用場景

String固定長度&#xff0c;引用的字符串內容無法改變例如&#xff0c;String s abc;s def;那么 s 字符串對應的地址已經改變了StringBuider 聲明一個對象時&#xff0c;指向堆中的一塊空間&#xff0c;包括兩個屬性 value 和 count其中 value 屬性類似動態數組&#xff0c;可…

Qualcomm Linux 藍牙指南學習--驗證 Fluoride 協議棧的功能(2)

前言 Qualcomm Technologies推出的Linux藍牙指南詳細介紹了基于Qualcomm RB3 Gen 2和IQ-9100 Beta開發套件的藍牙解決方案。該文檔涵蓋BlueZ和Fluoride協議棧的功能驗證流程,支持藍牙5.2核心規范,包括WCN6750/WCN6856/QCA6698AQ芯片組的特性。主要內容分為三部分: ?1. 功…

Spring Boot中REST與gRPC并存架構設計與性能優化實踐指南

Spring Boot中REST與gRPC并存架構設計與性能優化實踐指南 在微服務架構日益復雜的當下&#xff0c;單一協議往往難以滿足高并發低延遲與生態兼容的雙重需求。本文基于真實生產環境的項目經驗&#xff0c;分享了如何在Spring Boot中同時提供RESTful API和gRPC接口的架構設計、性…

Simulink仿真-model Setting關鍵配置

1.概述 Simulink 的仿真設置&#xff08;Model Settings&#xff09;是確保仿真準確性的關鍵配置&#xff0c;主要包括仿真時間、步長、解法器選擇等核心參數的設定。 ?可以通過快捷鍵?CtrlE?打開仿真設置界面2.核心參數 2.1 求解器Solver配置 時間范圍&#xff1a;設置仿真…

內網與外網是通過什么進行傳輸的?內外網文件傳輸的安全方法

在當前企業信息化建設日益深入的背景下&#xff0c;出于安全防護與合規管理的需要&#xff0c;很多單位將網絡劃分為內網&#xff08;辦公網/生產網&#xff09;與外網&#xff08;互聯網/DMZ區&#xff09;。這種網絡隔離策略雖然提升了安全性&#xff0c;但也帶來了內外網文件…

RabbitMQ面試精講 Day 4:Queue屬性與消息特性

【RabbitMQ面試精講 Day 4】Queue屬性與消息特性 開篇 歡迎來到"RabbitMQ面試精講"系列的第4天&#xff01;今天我們將深入探討RabbitMQ中Queue的屬性配置與消息特性&#xff0c;這是理解和優化RabbitMQ使用的關鍵知識點。掌握這些內容不僅能幫助你在面試中展現深厚…

uniapp vue3 vite項目使用微信云開發(云函數)

1、在根目錄新建文件夾 cloudfunctions2、配置 manifest.json在項目根目錄的 manifest.json 文件中&#xff0c;找到微信小程序配置部分&#xff0c;添加 cloudfunctionRoot 字段&#xff0c;指向你的云函數目錄&#xff1a;{"mp-weixin": {"cloudfunctionRoot&…

AK視頻下載工具:免費高效,多平臺支持

近期小編又發現了一款更強大的新神器——AK視頻下載&#xff08;電腦版&#xff09;&#xff0c;一起來了解下吧~ 軟件亮點 完全免費&#xff0c;無需安裝&#xff0c;操作便捷&#xff0c;直接打開即可使用。 支持多平臺視頻下載&#xff0c;包括抖音、B站、小紅書、快手等主…

7月21日星期一今日早報簡報微語報早讀

7月21日星期一&#xff0c;農歷六月廿七&#xff0c;早報#微語早讀。1、廣東佛山累計報告基孔肯雅熱確診病例1873例&#xff0c;均為輕癥&#xff1b;2、祝賀&#xff01;石宇奇奪得日本羽毛球公開賽男單冠軍&#xff1b;3、中國和匈牙利順利完成引渡條約談判&#xff1b;4、科…

基于Milvus Lite的輕量級向量數據庫實戰指南

一、為什么選擇Milvus Lite&#xff1f; 在人工智能和語義搜索應用中&#xff0c;高效的向量檢索是核心需求。相比需要部署Docker的完整版Milvus&#xff0c;Milvus Lite提供&#xff1a; 零依賴&#xff1a;純Python實現&#xff0c;無需安裝Docker或外部組件 開箱即用&…

深度學習時代下的社交媒體情感分析:方法、工具與未來挑戰

摘要&#xff1a;基于Yue等學者2019年發表的權威綜述&#xff0c;本文系統總結情感分析的技術框架、實戰資源與前沿方向&#xff0c;附Python代碼示例。 一、情感分析為何重要&#xff1f; 情感分析&#xff08;Sentiment Analysis&#xff09;旨在從文本中提取主觀態度&…

Spring Boot 3.0新特性全面解析與實戰應用

Spring Boot 3.0新特性全面解析與實戰應用 引言 Spring Boot 3.0作為Spring生態系統的一個重要里程碑&#xff0c;帶來了眾多令人興奮的新特性和改進。本文將深入解析Spring Boot 3.0的核心變化&#xff0c;并通過實戰示例展示如何在項目中應用這些新特性。 核心變化概覽 Java版…

C# sqlsugar 主子表 聯合顯示 LeftJoin

在C#中使用SqlSugar ORM進行Left Join操作是一種常見需求&#xff0c;尤其是在處理復雜數據庫查詢時。SqlSugar是一個輕量級、高性能的ORM框架&#xff0c;支持多種數據庫。下面是如何使用SqlSugar進行Left Join操作的示例。1. 安裝SqlSugar首先&#xff0c;確保你的項目中已經…