欢迎访问宙启技术站
智能推送

如何使用Python实现简单的爬虫

发布时间:2023-12-31 12:44:35

使用Python实现简单的爬虫可以分为以下几个步骤:

1. 导入相关库和模块:首先需要导入所需要的库和模块,常用的有requests、BeautifulSoup、re等。

import requests
from bs4 import BeautifulSoup
import re

2. 发送HTTP请求获取页面内容:使用requests库发送HTTP请求,获取页面的内容。

url = "http://example.com"
response = requests.get(url)
html = response.text

3. 解析页面内容:使用BeautifulSoup库对页面进行解析,提取所需的信息。

soup = BeautifulSoup(html, "html.parser")

4. 提取所需的信息:使用BeautifulSoup库提供的方法,提取页面中的所需信息,例如链接、标题、文本等。

# 提取所有链接
links = soup.find_all("a")

# 提取标题
title = soup.title.string

# 提取文本
text = soup.get_text()

5. 数据处理和存储:对提取到的信息进行必要的处理,如清洗、整理、过滤等,并将结果保存到文件或数据库中。

# 清洗文本
clean_text = re.sub(r"\s+", " ", text)

# 将结果保存到文件
with open("result.txt", "w", encoding="utf-8") as file:
    file.write(clean_text)

下面是一个简单的示例,演示如何使用Python实现一个简单的爬虫,获取豆瓣电影Top250的电影名和评分,并保存到文件中:

import requests
from bs4 import BeautifulSoup
import re

url = "https://movie.douban.com/top250"
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, "html.parser")

movies = soup.find_all("div", class_="info")

with open("douban_top250.txt", "w", encoding="utf-8") as file:
    for movie in movies:
        title = movie.find("span", class_="title").get_text()
        score = movie.find("span", class_="rating_num").get_text()
        file.write(f"电影名:{title},评分:{score}
")

以上就是使用Python实现简单的爬虫的基本步骤和一个示例。通过学习和实践,你可以进一步了解和掌握爬虫的更多技巧和方法。