欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 爬虫的bs4、xpath、requests、selenium、scrapy的基本用法

爬虫的bs4、xpath、requests、selenium、scrapy的基本用法

2024/10/25 21:27:45 来源:https://blog.csdn.net/weixin_44145338/article/details/141388995  浏览:    关键词:爬虫的bs4、xpath、requests、selenium、scrapy的基本用法

在 Python 中,BeautifulSoup(简称 bs4)、XPathRequestsSeleniumScrapy 是五种常用于网页抓取和解析的工具。

1. BeautifulSoup (bs4)

BeautifulSoup 是一个简单易用的 HTML 和 XML 解析库,常用于从网页中提取数据。
它的优点是易于学习和使用,适合处理静态页面的解析。

安装 BeautifulSoup
pip install beautifulsoup4
示例:解析 HTML 并提取数据
from bs4 import BeautifulSouphtml_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
<p class="story">...</p>
</body></html>
"""soup = BeautifulSoup(html_doc, 'html.parser')# 提取标题
print(soup.title.string)  # 输出: The Dormouse's story# 提取所有链接
for link in soup.find_all('a'):print(link.get('href'))

2. XPath

XPath 是一种用于从 XML 文档中选择节点的语言,它在解析和提取 HTML 内容时非常强大。
lxmlScrapy 等库支持使用 XPath。

示例:使用 lxml 和 XPath 提取数据
from lxml import etreehtml = """
<html><body>
<div><p class="title">Title 1</p><p class="content">Content 1</p>
</div>
<div><p class="title">Title 2</p><p class="content">Content 2</p>
</div>
</body></html>
"""tree = etree.HTML(html)# 提取所有标题
titles = tree.xpath('//p[@class="title"]/text()')
print(titles)  # 输出: ['Title 1', 'Title 2']

3. Requests

Requests 是一个用于发送 HTTP 请求的简单而强大的库,适合抓取静态网页内容。
它常与 BeautifulSouplxml 配合使用。

安装 Requests
pip install requests
示例:发送 HTTP 请求并获取网页内容
import requestsurl = 'http://example.com'
response = requests.get(url)if response.status_code == 200:print(response.text)  # 输出网页的 HTML 内容

4. Selenium

Selenium 是一个自动化工具,常用于需要浏览器交互或处理动态网页的抓取任务。
它可以模拟用户操作,如点击、输入、滚动等。

安装 Selenium 和浏览器驱动
pip install selenium

下载并配置浏览器驱动,如 chromedriver(Chrome)或 geckodriver(Firefox)。

示例:使用 Selenium 自动化浏览器操作
from selenium import webdriver
from selenium.webdriver.common.by import By# 启动 Chrome 浏览器
driver = webdriver.Chrome()# 打开网页
driver.get('http://example.com')# 查找元素并提取内容
element = driver.find_element(By.TAG_NAME, 'h1')
print(element.text)  # 输出页面上的第一个 <h1> 标签的文本# 关闭浏览器
driver.quit()

5. Scrapy

Scrapy 是一个功能强大的爬虫框架,适合大规模数据抓取。
它支持异步请求、数据处理管道、自动化抓取等功能,非常适合复杂的抓取任务。

安装 Scrapy
pip install scrapy
示例:创建并运行 Scrapy 爬虫
# 创建 Scrapy 项目
scrapy startproject myproject# 定义一个爬虫
import scrapyclass ExampleSpider(scrapy.Spider):name = 'example'start_urls = ['http://example.com']def parse(self, response):for title in response.xpath('//h1/text()').getall():yield {'title': title}# 运行爬虫
# 在命令行中执行: scrapy crawl example

工具选择指南

  • BeautifulSoup (bs4):适合解析静态 HTML,特别是简单的网页抓取任务。
  • XPath:强大的选择语言,用于复杂的 HTML/XML 解析,适合与 lxmlScrapy 一起使用。
  • Requests:用于发送 HTTP 请求,适合抓取静态网页内容。
  • Selenium:适合处理动态网页和需要模拟用户操作的场景。
  • Scrapy:适合大规模、复杂的网页抓取任务,支持异步处理和数据管道。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com