# 练习:采集电影信息(电影名称、电影评分、电影播放地址),保存到文本中。 # 目标地址:https://vip.1905.com/list/t_1/p1o6.shtml # 扩展(分页采集) # 了解其他网页结构(熟悉网页结构)
时间: 2025-06-28 16:21:29 浏览: 11
### 使用Python爬虫采集电影信息
为了实现从指定网址 `https://vip.1905.com/list/t_1/p1o6.shtml` 抓取电影信息(名称、评分、播放地址),并将这些数据保存到文本文件中,可以采用如下方法:
#### 导入必要的库
首先需要导入用于网络请求和HTML解析的相关库。
```python
import requests
from bs4 import BeautifulSoup
```
#### 获取页面内容
利用requests库发送HTTP GET请求获取网页源码。
```python
url = 'https://vip.1905.com/list/t_1/p{}.shtml' # 定义URL模式支持分页参数替换
headers = {'User-Agent': 'Mozilla/5.0'} # 设置头部信息防止被反爬机制阻止访问
response = requests.get(url.format(1), headers=headers)
content = response.text # 提取出响应体中的文本部分作为待处理的内容
soup = BeautifulSoup(content, 'lxml') # 创建BeautifulSoup对象以便于后续解析DOM树结构
```
#### 解析单页内的电影条目
遍历每一页上的所有影片列表项提取所需字段。
```python
movies = []
for item in soup.select('.list-item'):
title = item.find('a', class_='title').get_text(strip=True) or '' # 影片名
score = item.find('span', class_='score').get_text(strip=True) if item.find('span', class_='score') else '-' # 用户评价分数
play_url = item.find('a')['href'] # 播放链接
movies.append({
'name': title,
'rating': score,
'play_link': play_url
})
```
#### 实现多页循环抓取逻辑
考虑到存在多个子页面的情况,可以通过修改URL中的分页编号来迭代读取不同页面的数据。
```python
all_movies = []
def fetch_page(page_num):
url_with_page = url.format(page_num)
resp = requests.get(url_with_page, headers=headers)
if resp.status_code != 200:
print(f"Failed to load page {page_num}")
return False
html_doc = resp.content.decode()
parser = BeautifulSoup(html_doc, features="lxml")
for entry in parser.select(".list-item"):
movie_info = {
"name": (entry.find("a", {"class": "title"}).string.strip()
if entry.find("a", {"class": "title"}) is not None else ""),
"rating": ((entry.find("span", {"class": "score"}).text.strip())
if entry.find("span", {"class": "score"}) is not None else "-"),
"play_link": entry.a['href']
}
all_movies.append(movie_info)
current_page = 1
while True:
success = fetch_page(current_page)
if not success:
break
current_page += 1
```
#### 将收集的信息存储为TXT文档
最后一步是把之前累积下来的所有记录导出成纯文本格式存盘。
```python
with open('movie_data.txt', mode='w+', encoding='utf-8') as f:
for m in all_movies:
line = "\t".join([m["name"], str(m["rating"]), m["play_link"]]) + '\n'
f.write(line)
print("Data has been successfully saved.")
```
上述过程涵盖了完整的Web Scraping工作流,包括但不限于发起请求、解析HTML以及持久化结果等环节[^4]。
阅读全文
相关推荐
















