目錄
- 專欄導讀
- 📚 庫簡介
- 🎯 主要特點
- 🛠? 安裝方法
- 🚀 快速入門
- 基本使用流程
- 解析器選擇
- 🔍 核心功能詳解
- 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庫性能較低
- 內存占用:解析大文件時內存占用較高
🚀 最佳實踐建議
- 選擇合適的解析器:推薦使用lxml解析器
- 遵守網站規則:檢查robots.txt,設置合理延遲
- 錯誤處理:完善的異常處理和重試機制
- 數據清洗:對提取的數據進行驗證和清理
- 性能優化:使用緩存、并發等技術提高效率
-
BeautifulSoup配合requests庫,是Python爬蟲開發的經典組合,適合大多數網頁數據提取任務。掌握這個庫,將為你的數據采集工作提供強大的支持!
-
希望對初學者有幫助;致力于辦公自動化的小小程序員一枚
-
希望能得到大家的【??一個免費關注??】感謝!
-
求個 🤞 關注 🤞 +?? 喜歡 ?? +👍 收藏 👍
-
此外還有辦公自動化專欄,歡迎大家訂閱:Python辦公自動化專欄
-
此外還有爬蟲專欄,歡迎大家訂閱:Python爬蟲基礎專欄
-
此外還有Python基礎專欄,歡迎大家訂閱:Python基礎學習專欄