1. 数据抓取入门:豆瓣电影TOP250排行榜
在学习爬虫编程的初期,理解如何从网页中提取信息是至关重要的。以下是一个简单的实战案例,我们将从豆瓣电影的TOP250排行榜中抓取电影信息。
1.1 目标网页分析
首先,我们需要分析目标网页的HTML结构。通过查看源代码,我们可以找到电影列表的HTML元素,通常包含电影名称、评分、导演和演员等信息。
1.2 Python环境准备
使用Python进行爬虫开发,需要安装以下库:
requests:用于发送HTTP请求。BeautifulSoup:用于解析HTML文档。pandas:用于数据存储和分析。
1.3 编写爬虫代码
以下是一个简单的爬虫示例代码,用于从豆瓣电影TOP250排行榜中抓取电影名称和评分:
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_movie_info(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
movie_list = soup.find_all('div', class_='hd')
movies = []
for movie in movie_list:
title = movie.find('span').text
rating = movie.find('span', class_='rating_num').text
movies.append({'电影名称': title, '评分': rating})
return movies
url = 'https://movie.douban.com/top250'
movies = get_movie_info(url)
df = pd.DataFrame(movies)
print(df)
2. 社交媒体数据分析:分析微博用户关注数量
通过爬取社交媒体平台的数据,我们可以分析用户之间的关注关系,了解用户影响力等。
2.1 目标网页分析
以微博为例,我们需要分析微博用户个人主页的HTML结构,以找到关注人数的信息。
2.2 Python环境准备
同样,使用Python进行爬虫开发,需要安装以下库:
requestsBeautifulSouppandas
2.3 编写爬虫代码
以下是一个简单的爬虫示例代码,用于抓取微博用户个人主页的关注人数:
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_follow_count(url):
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
follow_count = soup.find('div', class_='tip2').find('strong').text
return follow_count
url = 'https://weibo.com/xxx' # 假设这是某个微博用户的个人主页
follow_count = get_follow_count(url)
print(f'该用户的关注人数为:{follow_count}')
3. 实时新闻抓取:抓取各大新闻网站的最新标题
实时抓取新闻网站的最新标题,可以帮助我们快速了解当前热点事件。
3.1 目标网页分析
分析新闻网站的HTML结构,找到最新新闻标题所在的HTML元素。
3.2 Python环境准备
安装以下库:
requestsBeautifulSouppandas
3.3 编写爬虫代码
以下是一个简单的爬虫示例代码,用于抓取新浪新闻网站的最新标题:
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_news_titles(url):
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
news_list = soup.find_all('a', class_='title')
titles = [news.get_text() for news in news_list]
return titles
url = 'http://news.sina.com.cn/'
news_titles = get_news_titles(url)
print(f'新浪新闻最新标题:{news_titles}')
通过以上实战案例,我们可以逐步掌握爬虫编程的基本技巧,并学会如何针对不同类型的数据源进行数据抓取。在实际应用中,我们需要不断积累经验,应对各种复杂的网页结构和反爬策略。祝你在爬虫编程的道路上越走越远!