Python 如何进行Web抓取(BeautifulSoup, Scrapy)

devtools/2024/10/18 18:27:24/

Web抓取(Web Scraping)是一种从网站提取数据的技术。Python有许多用于Web抓取的库,其中最常用的是BeautifulSoup和Scrapy。

BeautifulSoup

BeautifulSoup是一个用于解析HTML和XML文档的Python库,适合处理简单的Web抓取任务。它将复杂的HTML文档转换成一个可遍历的解析树,可以方便地找到需要的元素。

安装BeautifulSoup

要使用BeautifulSoup,首先需要安装它以及请求库requests:

pip install beautifulsoup4
pip install requests
导入BeautifulSoup
python">from bs4 import BeautifulSoup
import requests
获取网页内容

首先需要获取网页的HTML内容,可以使用requests库:

python">url = 'http://example.com'
response = requests.get(url)
html_content = response.content
解析HTML

使用BeautifulSoup解析HTML内容:

python">soup = BeautifulSoup(html_content, 'html.parser')
查找元素

BeautifulSoup提供了多种查找元素的方法,如findfind_allselect等。

python"># 查找第一个<p>标签
p_tag = soup.find('p')
print(p_tag.text)# 查找所有<a>标签
a_tags = soup.find_all('a')
for tag in a_tags:print(tag.get('href'))# 使用CSS选择器
header = soup.select_one('h1')
print(header.text)
处理属性

可以方便地获取标签的属性:

python">img_tag = soup.find('img')
print(img_tag['src'])
示例:抓取一个博客的标题和链接

以下是一个简单的示例,展示如何抓取一个博客页面的所有文章标题和链接:

python">url = 'http://example-blog.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')articles = soup.find_all('article')
for article in articles:title = article.find('h2').textlink = article.find('a')['href']print(f'Title: {title}, Link: {link}')

Scrapy

Scrapy是一个功能强大的Web抓取和Web爬虫框架,适用于复杂的抓取任务。它具有高性能、可扩展性强、支持异步处理等特点。

安装Scrapy

使用pip安装Scrapy:

pip install scrapy
创建Scrapy项目

首先需要创建一个Scrapy项目:

scrapy startproject myproject
cd myproject
创建爬虫

在Scrapy项目中,可以创建一个新的爬虫:

scrapy genspider myspider example.com

这将在spiders目录下生成一个名为myspider.py的文件。

编写爬虫

打开myspider.py,可以看到一个基本的爬虫模板。我们将修改这个模板来实现抓取任务。

python">import scrapyclass MySpider(scrapy.Spider):name = 'myspider'start_urls = ['http://example.com']def parse(self, response):# 解析响应for article in response.css('article'):title = article.css('h2::text').get()link = article.css('a::attr(href)').get()yield {'title': title,'link': link}
运行爬虫

在命令行中运行爬虫:

scrapy crawl myspider -o output.json

这将抓取example.com并将结果保存到output.json文件中。

Scrapy中的重要概念
  1. Item:定义抓取的数据结构。
  2. Spider:定义如何抓取网站的爬虫。
  3. Pipeline:定义数据处理和存储的流程。
  4. Middleware:处理请求和响应的中间件。
定义Item

可以在items.py中定义Item:

python">import scrapyclass MyprojectItem(scrapy.Item):title = scrapy.Field()link = scrapy.Field()

然后在爬虫中使用Item:

python">from myproject.items import MyprojectItemclass MySpider(scrapy.Spider):name = 'myspider'start_urls = ['http://example.com']def parse(self, response):for article in response.css('article'):item = MyprojectItem()item['title'] = article.css('h2::text').get()item['link'] = article.css('a::attr(href)').get()yield item
使用Pipeline处理数据

pipelines.py中定义Pipeline:

python">class MyprojectPipeline:def process_item(self, item, spider):# 处理itemreturn item

settings.py中启用Pipeline:

python">ITEM_PIPELINES = {'myproject.pipelines.MyprojectPipeline': 300,
}
示例:抓取一个电商网站的商品信息

以下是一个完整的示例,展示如何使用Scrapy抓取一个电商网站的商品信息。

首先定义Item:

python"># items.py
import scrapyclass ProductItem(scrapy.Item):name = scrapy.Field()price = scrapy.Field()availability = scrapy.Field()

然后编写爬虫:

python"># spiders/products_spider.py
import scrapy
from myproject.items import ProductItemclass ProductsSpider(scrapy.Spider):name = 'products'start_urls = ['http://example-ecommerce.com/products']def parse(self, response):for product in response.css('div.product'):item = ProductItem()item['name'] = product.css('h3.product-name::text').get()item['price'] = product.css('span.product-price::text').get()item['availability'] = product.css('span.availability::text').get()yield item# 处理分页next_page = response.css('a.next-page::attr(href)').get()if next_page:yield response.follow(next_page, self.parse)

最后启用Pipeline并运行爬虫:

python"># pipelines.py
class ProductPipeline:def process_item(self, item, spider):# 处理商品信息return item# settings.py
ITEM_PIPELINES = {'myproject.pipelines.ProductPipeline': 300,
}# 运行爬虫
scrapy crawl products -o products.json

BeautifulSoup和Scrapy各有优缺点,BeautifulSoup适合处理简单的抓取任务,使用方便,代码简洁;而Scrapy则更适合处理复杂的抓取任务,具有强大的功能和高效的性能。在实际项目中,可以根据具体需求选择合适的工具,甚至结合使用这两个库,以充分发挥各自的优势。


http://www.ppmy.cn/devtools/90755.html

相关文章

git常见问题(不定期更新)

1、文件名大小写问题 **问题描述&#xff1a;**默认情况下&#xff0c;在windows系统中&#xff0c;git不区分文件名大小写&#xff08;linux系统会区分&#xff09;&#xff0c;所以如果开发环境是windows系统的话&#xff0c;当我们修改文件名大小写时&#xff0c;git无法识…

Spring5 的日志学习

我们在使用 Spring5 的过程中会出现这样的现像&#xff0c;就是 Spring5 内部代码打印的日志和我们自己的业务代码打印日志使用的不是统一日志实现&#xff0c;尤其是在项目启动的时候&#xff0c;Spring5 的内部日志使用的是 log4j2&#xff0c;但是业务代码打印使用的可能是 …

k8s—Prometheus原理

一、Prometheus 1.Prometheus介绍 Prometheus 是一个开源的系统监控和报警系统&#xff0c;现在已经加入到 CNCF 基金会&#xff0c;成为继k8s 之后第二个在 CNCF 托管的项目&#xff0c;在 kubernetes 容器管理系统中&#xff0c;通常会搭配prometheus 进行监控&#xff0c;同…

C# Null 合并运算符 ??

int&#xff1f; 在 C# 中&#xff0c;int? 是一个可空的 int 类型&#xff0c;它能够存储一个 32 位带符号整数或者 null 值。当你声明一个 int? 类型的变量并将其初始化为 null&#xff0c;你实际上是在创建一个可以容纳整数值的变量&#xff0c;但是初始时并没有赋予它任…

案例分享-国外UI设计界面赏析

国外UI设计倾向于简洁的布局和清晰的排版&#xff0c;减少视觉干扰&#xff0c;提升用户体验。通过合理的色彩搭配和图标设计&#xff0c;营造舒适愉悦的使用氛围。 设计师不拘泥于传统框架&#xff0c;勇于尝试新元素和理念&#xff0c;使界面独特有趣。同时&#xff0c;强调以…

计算机基础(Windows 10+Office 2016)教程 —— 第4章 计算机网络与Internet(下)

第4章 计算机网络与Internet 4.4 局域网4.4.1 局域网概述4.4.2 以太网4.4.3 令牌环网4.4.4 无线局域网 4.5 Internet4.5.1 Internet 概述4.5.2 Internet 的基本概念4.5.3 Internet 的接入4.5.4 万维网 4.6 Internet的应用4.6.1 电子邮件4.6.2 文件传输4.6.3 搜索引擎 4.4 局域网…

数据结构:顺序表

目录 一、数据结构相关概念 二、顺序表的概念及结构 三、顺序表分类 四、动态顺序表的实现 4.1 头文件 4.2 各个功能的实现 4.2.1 初始化与销毁 4.2.2 申请空间 4.2.3 头插、尾插、头删、尾删 4.2.4 指定位置插入与删除 4.3 测试 五、完整源码 sxb.h sxb.c test.c 一…

CSP-J复赛 模拟题4

1. 删数游戏: 题目描述 两名同学在黑板上做删数游戏&#xff0c;游戏规则如下&#xff1a; 两名同学先一起在黑板上写了n个数字&#xff0c;同学A先擦掉一个数字&#xff0c;之后同学B再擦掉一个数字&#xff0c;轮流进行&#xff0c;直到黑板上只剩下最后一个数字&#xff…