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}')
相关推荐
逻辑驱动的ken10 小时前
Java高频面试考点场景题22
java·开发语言·jvm·面试·职场和发展·求职招聘·春招
傲笑风10 小时前
jupyter转PDF教程
python·jupyter
测试员周周10 小时前
【AI测试功能2】AI功能测试的“不可确定性“难题与应对思路:从精确断言到统计判定的完整方案
大数据·人工智能·python·功能测试·测试工具·单元测试·测试用例
枫叶丹410 小时前
【HarmonyOS 6.0】Core File Kit:端云文件版本管理能力解析与实践
开发语言·华为·harmonyos
初心未改HD10 小时前
Go 文件与 I/O 操作完全指南
开发语言·golang
szial11 小时前
uv 实战指南:用一个工具重塑 Python 开发工作流
开发语言·python·uv
Aision_11 小时前
为什么 CTI 场景需要知识图谱?
人工智能·python·安全·web安全·langchain·prompt·知识图谱
BU摆烂会噶11 小时前
【LangGraph】LangGraph 工具中访问运行时上下文——ToolRuntime
人工智能·python·langchain·人机交互
wjs202411 小时前
HTML 段落
开发语言
CSCN新手听安11 小时前
【Qt】Qt窗口(五)QDialog对话框的使用,点击按钮弹出新的对话框,自定义对话框界面,模态对话框model
开发语言·c++·qt