requests模块介绍
requests
是一个简单易用的HTTP库,允许你发送各种HTTP请求。它是Python爬虫的基础,因为它可以让我们以编程方式与网络服务器进行交互。
安装requests
首先,你需要安装requests
库,如果还没有安装,可以通过pip安装:
pip install requests
requests基本用法
以下是使用requests
发送GET请求的基本示例:
import requests
# 发送GET请求
response = requests.get('http://example.com')
# 打印响应的文本内容
print(response.text)
豆瓣电影排名爬取示例
下面是一个使用requests
爬取豆瓣电影排名的简单示例:
import requests
# 豆瓣电影Top 250的URL
url = 'https://movie.douban.com/top250'
# 发送GET请求
response = requests.get(url)
# 解析HTML内容
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含电影信息的元素
movies = soup.find_all('div', class_='item')
# 打印电影排名和名称
for movie in movies:
rank = movie.find('span', class_='rank').text
title = movie.find('span', class_='title').text
print(f'{rank}. {title}')
beautifulsoup4模块介绍
beautifulsoup4
是一个用于解析HTML和XML文档的库,它创建了一个解析树,方便我们提取数据。
安装beautifulsoup4
安装beautifulsoup4
库:
pip install beautifulsoup4
beautifulsoup4基本用法
以下是使用beautifulsoup4
解析HTML的基本示例:
from bs4 import BeautifulSoup
# 假设我们有一段HTML内容
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
"""
# 解析HTML
soup = BeautifulSoup(html_doc, 'html.parser')
# 获取标题
title = soup.title
print(f"Title: {title.string}")
常见用法
- 查找标签:使用
find
或find_all
方法查找标签。 - 属性访问:使用点操作符访问标签的属性。
- 文本提取:使用
.text
或.string
提取文本内容。