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

Python脚本爬取目标网站上的所有链接

一、爬取后txt文件保存

需要先pip install requests和BeautifulSoup库

import requests
from bs4 import BeautifulSoup# 定义要爬取的新闻网站URL
url = 'https://www.chinadaily.com.cn/'  # China Daily 网站# 发送请求获取页面内容
response = requests.get(url)# 检查请求是否成功
if response.status_code == 200:print('Successfully retrieved the website.')# 解析网页内容soup = BeautifulSoup(response.text, 'html.parser')# 打开一个文件以写入爬取的数据with open('news_data.txt', 'w', encoding='utf-8') as f:# 选择网站上合适的新闻标签for item in soup.find_all('a', href=True):  # 这里使用<a>标签,因为它包含链接title = item.get_text().strip()  # 获取标题link = item['href']  # 获取链接# 过滤掉无效的标题或链接if title and 'http' in link:# 将标题和链接写入文件f.write(f'链接标题: {title}\n链接地址: {link}\n\n')print("Data saved to 'news_data.txt'.")
else:print(f'Failed to retrieve the website. Status code: {response.status_code}')

二、 爬取后csv文件保存

import requests
from bs4 import BeautifulSoup
import csv# 定义要爬取的新闻网站URL
url = 'https://www.chinadaily.com.cn/'  # 示例网站# 发送请求获取页面内容
response = requests.get(url)# 手动设置编码为utf-8(如果页面是使用utf-8编码)
response.encoding = 'utf-8'  # 确保使用正确的编码格式# 检查请求是否成功
if response.status_code == 200:print('Successfully retrieved the website.')# 解析网页内容soup = BeautifulSoup(response.text, 'html.parser')# 打开一个CSV文件以写入爬取的数据with open('news_data.csv', 'w', newline='', encoding='utf-8') as f:writer = csv.writer(f)writer.writerow(['Title', 'Link'])  # 写入标题行# 查找所有包含链接的<a>标签for item in soup.find_all('a', href=True):title = item.get_text().strip()  # 获取标题link = item['href']  # 获取链接# 过滤掉无效的标题或链接if title and link:writer.writerow([title, link])print("Data saved to 'news_data.csv'.")
else:print(f'Failed to retrieve the website. Status code: {response.status_code}')

http://www.lryc.cn/news/460717.html

相关文章:

  • Linux下以编译源码的方式安装Qt5与Qt6及其使用
  • 替换掉js后重启nginx 页面加载后js还是原来的 解决方法.【js版本号】【js不生效】【js失效】
  • SHELL脚本之输出语句的使用
  • 《大规模语言模型从理论到实践》第一轮学习--Fine-tuning微调
  • XGBoost回归预测 | MATLAB实现XGBoost极限梯度提升树多输入单输出
  • 【翻译】在 Python 应用程序中使用Qt Designer的UI文件
  • 002-Html
  • 微知-Mellanox提供的一个不错的测试rdma_cm方式建链的工具软件ucmatose?(ucmatose; ucmatose -s 1.1.1.1)
  • Vivado HLS C/RTL 联合仿真时间
  • Python实现图像加密与解密工具
  • 《RabbitMQ篇》消费者轮询消费消息
  • mongodb导入导出
  • 判断 HTTP/2 多路复用是否在服务器上实现
  • (已解决)vscode使用launch.json进行debug调试报错:Couldn‘t spawn debuggee:embedded null byte
  • windows桌面便签小工具,便签软件哪个好用?
  • 【Linux】C文件头文件数裁剪前58644个,裁剪后9373个
  • 线性自抗扰控制(LADRC)系统算法框图
  • 基于SSM的微信小程序博客管理系统(博客1)
  • text-behind-image:轻松创建文字背景图片设计
  • 前端reactvue3——实现滚动到底加载数据
  • qt 安装提示 无法定位程序输入点 systemparametersinfofordpi于动态链接库
  • 算法笔记day04
  • 实战篇:(四)Vue2 + Three.js 创建可交互的360度全景视图,可控制旋转、缩放完整代码
  • 【load_file读文件】
  • JavaScript object(2)
  • Acwing 排序
  • 分布式环境下验证码登录的技术实现
  • 数据结构-5.9.树的存储结构
  • 【Linux】解锁线程基本概念和线程控制,步入多线程学习的大门
  • uniapp学习(005-2 详解Part.2)