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}')
相关推荐
一个天蝎座 白勺 程序猿2 小时前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
XiaoMu_0013 小时前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
honder试试4 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky4 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
心本无晴.4 小时前
Python进程,线程
python·进程
ponnylv4 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人4 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
Jayden_Ruan5 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊5 小时前
启动文件Startup_vle.c
c语言·开发语言
VBA63375 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言