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

一、爬取后txt文件保存

需要先pip install requests和BeautifulSoup库

python 复制代码
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文件保存

python 复制代码
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}')
相关推荐
wefly201710 小时前
M3U8 播放调试天花板!m3u8live.cn纯网页无广告,音视频开发效率直接拉满
java·前端·javascript·python·音视频
敷衍一下X11 小时前
Selenium元素定位
python·selenium·测试工具
与虾牵手11 小时前
Redis 缓存穿透,我在线上被教做人的全过程(附 3 种方案 + 代码)
python
lisus200711 小时前
GO并发统计文件大小
开发语言·后端·golang
梦游钓鱼11 小时前
Logger.h和Logger.cc文件分析
开发语言·c++
CRMEB系统商城11 小时前
CRMEB标准版系统(PHP)v6.0公测版发布,商城主题市场上线~
java·开发语言·小程序·php
安逸sgr11 小时前
【端侧 AI 实战】BitNet 详解:1-bit LLM 推理优化从原理到部署!
人工智能·python·scrapy·fastapi·ai编程·claude
我爱学习好爱好爱11 小时前
ELK日志分析平台(三):Logstash 7.17.10 独立节点部署与基础测试(基于Rocky Linux 9.6)
linux·python·elk
yangminlei11 小时前
openclaw对接飞书
开发语言·python·飞书
minglie111 小时前
Amaranth HDL
python·fpga开发