> 技术文档 > Python 数据爬取(爬虫):从零开始学会爬取网页数据

Python 数据爬取(爬虫):从零开始学会爬取网页数据


在现代互联网时代,数据爬取已经成为获取网络数据的重要方式。通过编写爬虫程序,用户可以从网页中提取各种信息,如新闻、商品数据、社交媒体内容等。Python 作为一门简洁且强大的编程语言,提供了许多强大的库来帮助开发爬虫。

本文将带你从基础到进阶,学习如何使用 Python 进行网页数据的爬取,包括使用 requestsBeautifulSoupSelenium 等工具进行数据抓取,并提供丰富的代码示例。

1. 基础知识

1.1 网络请求基础

爬虫的核心在于向网站发送 HTTP 请求,获取网页内容。常用的 HTTP 请求方法有 GET 和 POST。我们常常使用 requests 库来发送这些请求。

安装 requests 库

首先,你需要安装 requests 库:

pip install requests

1.2 发送 GET 请求

GET 请求用于从指定的资源(如网页)获取数据。

import requestsurl = \"https://www.example.com\" # 替换为你想爬取的网页地址response = requests.get(url)# 打印网页内容print(response.text)

1.3 发送 POST 请求

POST 请求通常用于向服务器提交数据。

url = \"https://www.example.com/login\"payload = {\'username\': \'user\', \'password\': \'pass\'}response = requests.post(url, data=payload)# 打印服务器响应内容print(response.text)

2. 解析网页数据:BeautifulSoup

在爬取网页数据之后,通常需要解析 HTML 内容。BeautifulSoup 是一个非常强大的 HTML 解析库,它能够帮助我们从网页中提取所需的信息。

2.1 安装 BeautifulSoup

pip install beautifulsoup4

2.2 使用 BeautifulSoup 解析网页

from bs4 import BeautifulSoupimport requestsurl = \"https://www.example.com\"response = requests.get(url)# 使用 BeautifulSoup 解析 HTML 内容soup = BeautifulSoup(response.text, \'html.parser\')# 打印网页标题print(soup.title)# 打印网页中所有的链接for link in soup.find_all(\'a\'): print(link.get(\'href\'))

2.3 提取指定元素

你可以根据标签、类名、id 等提取指定的元素。

# 获取特定 ID 元素element = soup.find(id=\"main-content\")print(element)# 获取所有具有特定 class 的元素elements = soup.find_all(class_=\"article\")for item in elements: print(item.text)

3. 爬取动态网页:Selenium

有些网页的内容是通过 JavaScript 动态加载的,使用 requestsBeautifulSoup 无法直接获取。这时,我们需要借助 Selenium,它可以模拟浏览器操作,获取网页中的动态内容。

3.1 安装 Selenium 和 WebDriver

pip install selenium

同时,你需要安装相应浏览器的 WebDriver。例如,使用 Chrome 浏览器时,下载 ChromeDriver,并将其路径添加到系统环境变量中。

3.2 使用 Selenium 抓取动态网页

from selenium import webdriverfrom selenium.webdriver.common.by import Byimport time# 设置浏览器驱动driver = webdriver.Chrome(executable_path=\"/path/to/chromedriver\")# 打开网页url = \"https://www.example.com\"driver.get(url)# 等待网页加载time.sleep(3)# 获取网页标题print(driver.title)# 获取动态加载的元素element = driver.find_element(By.ID, \"dynamic-element\")print(element.text)# 关闭浏览器driver.quit()

3.3 滚动页面抓取

对于需要滚动加载的网页,我们可以模拟滚动操作,获取更多的数据。

from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timedriver = webdriver.Chrome(executable_path=\"/path/to/chromedriver\")url = \"https://www.example.com\"driver.get(url)# 模拟按下向下箭头键body = driver.find_element(By.TAG_NAME, \"body\")body.send_keys(Keys.PAGE_DOWN)# 等待页面加载time.sleep(2)# 获取页面内容content = driver.page_sourceprint(content)# 关闭浏览器driver.quit()

4. 批量抓取:循环抓取多页数据

许多网站会分页显示内容,爬虫需要模拟翻页操作,抓取多个页面的数据。你可以通过修改 URL 中的页码参数来抓取多个页面。

4.1 抓取多页数据

import requestsfrom bs4 import BeautifulSoupbase_url = \"https://www.example.com/page=\"# 假设网页有 5 页for page_num in range(1, 6): url = base_url + str(page_num) response = requests.get(url) soup = BeautifulSoup(response.text, \'html.parser\') # 处理每页的数据 articles = soup.find_all(\'article\') for article in articles: title = article.find(\'h2\').text print(title)

4.2 数据存储:保存到 CSV 文件

爬取的数据可以存储到 CSV 文件中,以便后续分析。

import csvimport requestsfrom bs4 import BeautifulSoup# 打开 CSV 文件以写入with open(\"articles.csv\", mode=\'w\', newline=\'\', encoding=\'utf-8\') as file: writer = csv.writer(file) writer.writerow([\"Title\", \"URL\"]) # 循环抓取多个页面 base_url = \"https://www.example.com/page=\" for page_num in range(1, 6): url = base_url + str(page_num) response = requests.get(url) soup = BeautifulSoup(response.text, \'html.parser\') # 解析并写入数据 articles = soup.find_all(\'article\') for article in articles: title = article.find(\'h2\').text link = article.find(\'a\')[\'href\'] writer.writerow([title, link])

5. 反爬虫策略与解决方案

许多网站为了防止被爬虫抓取,会采取反爬虫措施。常见的反爬虫策略包括:

  • IP 限制:同一 IP 请求次数过多会被封禁。
  • 验证码:通过验证码验证是否为人类访问。
  • User-Agent 检测:检查请求头是否符合浏览器标准。

5.1 设置 User-Agent

通过修改请求头中的 User-Agent 字段,可以模拟浏览器请求。

import requestsheaders = { \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\"}url = \"https://www.example.com\"response = requests.get(url, headers=headers)print(response.text)

5.2 使用代理

通过使用代理 IP,可以避免同一 IP 被封禁。

import requestsproxies = { \"http\": \"http://123.123.123.123:8080\", \"https\": \"https://123.123.123.123:8080\"}url = \"https://www.example.com\"response = requests.get(url, proxies=proxies)print(response.text)

总结

本文介绍了如何使用 Python 编写简单的网页爬虫程序,涵盖了静态网页的抓取、动态网页抓取、批量抓取、数据存储和反爬虫策略等内容。通过 requestsBeautifulSoupSelenium 等工具,我们能够高效地抓取各种网页数据。

编写爬虫时,请遵循法律法规,尊重网站的隐私政策和 robots.txt 文件的规定,合理使用爬虫工具。

希望这篇文章能帮助你顺利入门 Python 爬虫的世界,开始构建自己的数据抓取应用!