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}')
相关推荐
笃行客从不躺平5 分钟前
线程池原理复习
java·开发语言
A尘埃15 分钟前
大模型应用python+Java后端+Vue前端的整合
java·前端·python
A尘埃20 分钟前
LLM大模型评估攻略
开发语言·python
littlepeanut.top21 分钟前
C++中将FlatBuffers序列化为JSON
开发语言·c++·json·flatbuffers
一晌小贪欢43 分钟前
【Python办公】处理 CSV和Excel 文件操作指南
开发语言·python·excel·excel操作·python办公·csv操作
清风与日月1 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
是苏浙1 小时前
零基础入门C语言之贪吃蛇的实现
c语言·开发语言·数据结构
化作星辰1 小时前
java 给鉴权kafka2.7(sasl)发送消息权限异常处理
java·大数据·开发语言·kafka
无极小卒1 小时前
如何在三维空间中生成任意方向的矩形内部点位坐标
开发语言·算法·c#
克里斯蒂亚诺更新1 小时前
微信小程序 点击某个marker改变其大小
开发语言·前端·javascript