根據作業系統選擇適合的安裝方式:
easy_install beautifulsoup4pip install beautifulsoup4,注意 PyPI 上的 BeautifulSoup 是舊版 3.x,不建議安裝。apt-get install python-bs4python setup.py install# coding=utf-8
''' 通過 BeautifulSoup 下載百度貼吧圖片 '''
import urllib
from bs4 import BeautifulSoup
url = 'https://tieba.baidu.com/p/3537654215'
html = urllib.urlopen(url)
content = html.read()
html.close()
soup = BeautifulSoup(content)
# 使用 CSS 選擇器定位圖片,比正則更簡潔
all_img_links = soup.findAll('img', class_='BDE_Image')
img_counter = 1
for img_link in all_img_links:
img_name = '%s.jpg' % img_counter
urllib.urlretrieve(img_link['src'], img_name)
img_counter += 1
首先手動觀察目標頁面 https://pyvideo.org/category/50/pycon-us-2014 的 HTML 結構,確定視頻列表容器與鏈接位置。
使用 requests 獲取頁面:
import requests
response = requests.get('https://pyvideo.org/category/50/pycon-us-2014')
利用 BeautifulSoup 的 CSS 選擇器提取視頻詳情頁鏈接:
import bs4
soup = bs4.BeautifulSoup(response.text)
links = [a.attrs.get('href') for a in soup.select('div.video-summary-data a[href^=/video]')]
遍歷每個視頻頁,提取標題、講者、YouTube 鏈接,再請求 YouTube 頁面解析觀看數、讚/踩數:
def get_video_data(video_page_url):
video_data = {}
response = requests.get(root_url + video_page_url)
soup = bs4.BeautifulSoup(response.text)
video_data['title'] = soup.select('div#videobox h3')[0].get_text()
video_data['speakers'] = [a.get_text() for a in soup.select('div#sidebar a[href^=/speaker]')]
video_data['youtube_url'] = soup.select('div#sidebar a[href^=https://www.youtube.com]')[0].get_text()
# 解析 YouTube 頁面
response = requests.get(video_data['youtube_url'])
soup = bs4.BeautifulSoup(response.text)
video_data['views'] = int(re.sub('[^0-9]', '', soup.select('.watch-view-count')[0].get_text().split()[0]))
video_data['likes'] = int(re.sub('[^0-9]', '', soup.select('.likes-count')[0].get_text().split()[0]))
video_data['dislikes'] = int(re.sub('[^0-9]', '', soup.select('.dislikes-count')[0].get_text().split()[0]))
return video_data
單線程版本耗時 75 秒,引入 multiprocessing.Pool 後僅需 16 秒:
from multiprocessing import Pool
def show_video_stats(options):
pool = Pool(options.workers)
video_page_urls = get_video_page_urls()
results = pool.map(get_video_data, video_page_urls)
# 後續排序與輸出邏輯...
建議進程數為 CPU 核心數的 2 倍(如 8 核設為 8),過大反而無提升。
--sort 按 views/likes/dislikes 排序--max 限制輸出條數--csv 輸出 CSV 格式--workers 自定義並發數完整代碼整合了參數解析、多進程抓取、數據清洗與多格式輸出,可直接作為生產級爬蟲模板。