当前位置: 首页 > news >正文

《人生苦短,我用python·十一》python网络爬虫的简单使用

Python 有很多库可以用于网络爬虫,最常用的包括 requests 和 BeautifulSoup。以下是如何使用这些库来爬取数据的详细步骤和示例。

1. 安装依赖库
首先,确保安装了 requests 和 BeautifulSoup 库。如果还没有安装,可以使用以下命令进行安装:

pip install requests
pip install beautifulsoup4

2. 使用 requests 库获取网页内容
requests 库用于发送 HTTP 请求并接收响应。以下是获取网页内容的示例:

import requestsurl = 'https://example.com'
response = requests.get(url)if response.status_code == 200:html_content = response.textprint(html_content)
else:print(f"Failed to retrieve the webpage. Status code: {response.status_code}")

3. 使用 BeautifulSoup 解析 HTML 内容
BeautifulSoup 是一个用于解析 HTML 和 XML 文档的库。以下是解析 HTML 内容的示例:

from bs4 import BeautifulSoupsoup = BeautifulSoup(html_content, 'html.parser')# 查找所有的标题标签
titles = soup.find_all('h1')
for title in titles:print(title.get_text())# 查找特定的标签
specific_div = soup.find('div', {'class': 'specific-class'})
if specific_div:print(specific_div.get_text())

4. 综合示例
以下是一个综合示例,演示如何从一个新闻网站爬取标题和链接:

import requests
from bs4 import BeautifulSoupurl = 'https://news.ycombinator.com/'
response = requests.get(url)if response.status_code == 200:html_content = response.textsoup = BeautifulSoup(html_content, 'html.parser')# 查找所有新闻条目stories = soup.find_all('a', {'class': 'storylink'})for story in stories:title = story.get_text()link = story['href']print(f"Title: {title}")print(f"Link: {link}\n")
else:print(f"Failed to retrieve the webpage. Status code: {response.status_code}")

5. 处理分页
有些网站的数据分布在多个页面上,需要处理分页。以下是处理分页的示例:

import requests
from bs4 import BeautifulSoupbase_url = 'https://example.com/page/'
page_number = 1while True:url = f"{base_url}{page_number}"response = requests.get(url)if response.status_code != 200:breakhtml_content = response.textsoup = BeautifulSoup(html_content, 'html.parser')items = soup.find_all('div', {'class': 'item'})if not items:breakfor item in items:title = item.find('h2').get_text()print(title)page_number += 1

6. 处理动态内容
对于动态生成的内容,如通过 JavaScript 加载的内容,可以使用 Selenium 库。安装方法:

pip install selenium

使用 Selenium 获取动态内容的示例:

from selenium import webdriverurl = 'https://example.com'
driver = webdriver.Chrome()  # 或者使用其他浏览器的驱动程序
driver.get(url)html_content = driver.page_source
soup = BeautifulSoup(html_content, 'html.parser')# 解析内容
items = soup.find_all('div', {'class': 'item'})
for item in items:title = item.find('h2').get_text()print(title)driver.quit()

7. 爬虫礼仪
遵守网站的 robots.txt 文件:这个文件定义了哪些页面允许被爬取。
设置适当的请求间隔:避免频繁请求,给服务器带来负担。
使用 User-Agent:在请求头中添加 User-Agent,表明请求是由浏览器发出的。

headers = {'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'
}response = requests.get(url, headers=headers)

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 基于Hutool实现自定义模板引擎,实现json个性化模板引擎转换
  • 机器学习 | 回归算法原理——最小二乘法
  • SQL labs-SQL注入(三)
  • 离散型以及连续型随机变量
  • 【JVM基础05】——组成-能不能解释一下方法区?
  • 手机如何播放电脑的声音?
  • Django 简介
  • Unity UGUI 之 Slider
  • .NET开源、简单、实用的数据库文档生成工具
  • Windows 11+Visual Studio 2022 环境OpenCV+CUDA 12.5安装及踩坑笔记
  • 23种设计模式【结构型模式】详细介绍之【组合模式】
  • 【分布式锁】Redission实现分布式锁
  • 杰发科技Bootloader(1)—— Keil配置地址
  • Vuex数据持久化实现
  • 若依Vue前后端分离版如何部署(windows)(超详细)
  • SegmentFault for Android 3.0 发布
  • [deviceone开发]-do_Webview的基本示例
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • 【跃迁之路】【733天】程序员高效学习方法论探索系列(实验阶段490-2019.2.23)...
  • CentOS 7 修改主机名
  • Create React App 使用
  • css选择器
  • ES学习笔记(10)--ES6中的函数和数组补漏
  • JavaScript设计模式之工厂模式
  • Java小白进阶笔记(3)-初级面向对象
  • leetcode98. Validate Binary Search Tree
  • Spring Cloud中负载均衡器概览
  • 创建一种深思熟虑的文化
  • 今年的LC3大会没了?
  • 深入浏览器事件循环的本质
  • 数据库写操作弃用“SELECT ... FOR UPDATE”解决方案
  • 王永庆:技术创新改变教育未来
  • 微服务入门【系列视频课程】
  • 一天一个设计模式之JS实现——适配器模式
  • 译自由幺半群
  • puppet连载22:define用法
  • 阿里云移动端播放器高级功能介绍
  • 直播平台建设千万不要忘记流媒体服务器的存在 ...
  • ​ 无限可能性的探索:Amazon Lightsail轻量应用服务器引领数字化时代创新发展
  • $nextTick的使用场景介绍
  • (31)对象的克隆
  • (C语言)字符分类函数
  • (leetcode学习)236. 二叉树的最近公共祖先
  • (Ruby)Ubuntu12.04安装Rails环境
  • (附源码)spring boot校园拼车微信小程序 毕业设计 091617
  • (译)2019年前端性能优化清单 — 下篇
  • (转)C#调用WebService 基础
  • ... 是什么 ?... 有什么用处?
  • ..回顾17,展望18
  • .[hudsonL@cock.li].mkp勒索加密数据库完美恢复---惜分飞
  • .Net CF下精确的计时器
  • .net core 使用js,.net core 使用javascript,在.net core项目中怎么使用javascript
  • @TableLogic注解说明,以及对增删改查的影响
  • [2544]最短路 (两种算法)(HDU)
  • [acm算法学习] 后缀数组SA