You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改Python爬虫:仅抓取链接、从TXT读取待爬URL的问题

Python爬虫代码修改方案

问题1:删除name_list后DataFrame为空的修正

删除name_list相关代码后,需注意两个核心点:

  • 保留链接抓取逻辑:确保循环中仅专注收集链接列表,不要误删append()的代码
  • 正确构造DataFrame:仅传入包含Link列的字典,而非原代码中包含Name的结构
  • 精准筛选链接:如果目标链接有固定URL模式(如https://www.example.com/video/xxx),直接通过href属性前缀筛选,比依赖class选择器更可靠

问题2:从TXT读取待爬URL并逐行抓取

  1. 准备待爬URL文件:创建target_urls.txt,每行写入一个待爬页面URL,示例:
https://www.examples.com/user/username#page1-videos
https://www.examples.com/user/username#page2-videos
https://www.examples.com/user/username#page3-videos
...
https://www.examples.com/user/username#page10-videos
  1. 代码读取逻辑:通过文件读取函数逐行加载URL,去除换行符和空白字符后逐个请求

修改后的完整代码

import requests
from bs4 import BeautifulSoup
import pandas as pd

# 从TXT文件读取待爬URL
def load_target_urls(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        # 过滤空行并去除换行符
        urls = [line.strip() for line in f if line.strip()]
    return urls

# 初始化存储链接的列表
video_links = []

# 加载待爬URL列表
target_urls = load_target_urls('target_urls.txt')

# 遍历每个URL进行抓取
for page_url in target_urls:
    print(f"正在处理页面: {page_url}")
    try:
        # 发送请求,添加异常处理避免程序崩溃
        response = requests.get(page_url)
        response.raise_for_status()
        
        # 解析页面HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 筛选符合目标模式的链接(href以指定前缀开头)
        for link_tag in soup.select('a[href^="https://www.example.com/video/"]'):
            full_link = link_tag['href']
            video_links.append(full_link)
            print(f"捕获链接: {full_link}")
            
    except Exception as e:
        print(f"页面{page_url}抓取失败: {str(e)}")
        continue

# 保存抓取结果
if video_links:
    # 保存为CSV文件(带表头)
    df = pd.DataFrame({'Link': video_links})
    df.to_csv('captured_links.csv', index=False)
    print("CSV结果文件已生成")
    
    # 保存为TXT文件(每行一个链接)
    with open('captured_links.txt', 'w', encoding='utf-8') as f:
        f.write('\n'.join(video_links))
    print("TXT结果文件已生成")
else:
    print("未抓取到任何链接,请检查页面选择器或网络连接")

关键说明

  • 链接筛选:使用a[href^="https://www.example.com/video/"]直接匹配目标URL模式,无需依赖页面class,适配性更强
  • 异常处理:对每个页面请求添加错误捕获,避免单个页面出错导致整个爬虫终止
  • 结果输出:同时支持CSV和TXT两种格式,满足预期需求

内容的提问来源于stack exchange,提问作者Edwin Szeto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:35:55