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}')
相关推荐
witAI11 分钟前
**AI仿真人剧制作2025推荐,专业团队与创新技术引领未来**
人工智能·python
liuyao_xianhui18 分钟前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
做一个AK梦19 分钟前
计算机系统概论知识点(软件设计师)
java·开发语言
♪-Interpretation27 分钟前
第五节:Python的流程控制语句
python
東雪木37 分钟前
Java学习——一访问修饰符(public/protected/default/private)的权限控制本质
java·开发语言·学习·java面试
cch891841 分钟前
易语言与C++:编程语言终极对决
开发语言·c++
shark22222221 小时前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
551只玄猫1 小时前
【数学建模 matlab 实验报告6】行遍性问题
开发语言·数学建模·matlab
m0_564876842 小时前
提示词工程手册学习
人工智能·python·深度学习·学习
Blurpath住宅代理2 小时前
社交媒体数据采集技术指南:从合规获取到营销洞察
网络·爬虫·动态代理·数据抓取·住宅ip·住宅代理