Python编写简单爬虫


Python编写简单爬虫

在这里插入图片描述

安装必要的库

在开始编写爬虫之前,你需要安装一些必要的库。我们将使用requests库来发送HTTP请求,使用BeautifulSoup库来解析HTML内容。你可以使用以下命令来安装它们:

pip install requests beautifulsoup4
编写爬虫代码

下面是一个简单的爬虫示例,它从豆瓣电影Top250页面抓取电影标题和评分:

import requests
from bs4 import BeautifulSoup

# 目标URL
url = "https://movie.douban.com/top250"

# 发送HTTP请求
response = requests.get(url)
response.encoding = 'utf-8'

# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')

# 查找所有电影条目
movies = soup.find_all('div', class_='item')

# 提取电影标题和评分
for movie in movies:
    title = movie.find('span', class_='title').text
    rating = movie.find('span', class_='rating_num').text
    print(f"电影标题: {
      
      title}, 评分: {
      
      rating}")

在这里插入图片描述

解析和存储数据

你可以根据需要进一步解析和存储数据,例如将数据保存到CSV文件或数据库中。以下是将数据保存到CSV文件的示例:

import csv

# 打开CSV文件
with open('movies.csv', 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['title', 'rating']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    # 写入表头
    writer.writeheader()

    # 写入电影数据
    for movie in movies:
        title = movie.find('span', class_='title').text
        rating = movie.find('span', class_='rating_num').text
        writer.writerow({
    
    'title': title, 'rating': rating})
注意事项
  • 遵守网站的robots.txt规则:确保你的爬虫遵守目标网站的robots.txt文件中的爬取规则。
  • 避免频繁请求:添加适当的延迟(如使用time.sleep)以避免对目标网站造成过大压力。
  • 处理反爬机制:一些网站可能会有反爬机制,你需要处理如验证码、IP封禁等问题。

通过这些步骤,你可以编写一个简单的Python爬虫来抓取网页数据。

猜你喜欢

转载自blog.csdn.net/weixin_46412417/article/details/140124891