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}')
相关推荐
爱吃小胖橘14 分钟前
Lua语法(2)
开发语言·unity·lua
_Power_Y16 分钟前
SSM面试题学习
java·开发语言·学习
Pocker_Spades_A27 分钟前
中秋与代码共舞:用Python、JS、Java打造你的专属中秋技术盛宴
python
梁萌36 分钟前
自动化测试框架playwright使用
自动化测试·python·ui自动化·playwright
SccTsAxR40 分钟前
[初学C语言]关于scanf和printf函数
c语言·开发语言·经验分享·笔记·其他
Python×CATIA工业智造1 小时前
Python回调函数中携带额外状态的完整指南:从基础到高级实践
python·pycharm
害恶细君1 小时前
【超详细】使用conda配置python的开发环境
开发语言·python·jupyter·pycharm·conda·ipython
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 变量(Variable)的定义与操作
python·深度学习·tensorflow·tensorflow2
我星期八休息2 小时前
C++异常处理全面解析:从基础到应用
java·开发语言·c++·人工智能·python·架构
2401_841495642 小时前
【数据结构】汉诺塔问题
java·数据结构·c++·python·算法·递归·