You need to enable JavaScript to run this app. Python爬虫用BeautifulSoup遍历div.col-12时无法正确提取目标文本
优惠活动
大模型
产品
解决方案
定价
更多

Python爬虫用BeautifulSoup遍历div.col-12时无法正确提取目标文本

问题原因及修复方案

核心问题点

  • for...else逻辑使用错误:Python中for...else的else分支会在for循环没有被break主动中断时无条件执行,你当前的写法只要遍历完所有a标签(无论有没有匹配结果),都会直接执行break跳出外层while循环,导致后面的字段提取、翻页逻辑根本无法按预期执行。
  • 字段赋值顺序颠倒:从你给出的HTML结构可知,每个带row的col-12容器内,三个row的内容顺序依次是date、name(source)、number,但你代码中写的是name.append(row[0])、date.append(row[1]),直接把前两个字段的赋值顺序搞反,是你字段内容异常的核心原因。
  • 文本提取缺少容错处理:你使用entry.find_all(text=True, recursive=False)提取文本时,如果目标节点下没有直接文本节点,target[0]会触发索引报错,也可能返回空字符串strip后得到空值,建议增加容错判断。

修正后代码

from bs4 import BeautifulSoup as bs
import time
from selenium.webdriver import ActionChains

title,date,name,number = [],[],[],[]
while True:
    soup = bs(driver.page_source, 'html5lib')
    # 修正获取title的逻辑,找不到title才终止循环
    a_list = soup.find_all('a', attrs={'title':'ad i'})
    if not a_list:
        break
    for div in a_list:
        titl = div.get_text(strip=True)
        title.append(titl)
    
    for col in soup.find_all('div', attrs={'class':'col-12'})[1::2]:
        row = []
        for entry in col.select('div.row div'):
            # 提取直接子文本,增加容错处理,同时过滤字段前缀
            target = entry.find_all(text=True, recursive=False)
            if target:
                text = target[0].strip()
                # 可选操作:去掉date:、source:、number:这类前缀
                text = text.split(":", 1)[-1].strip()
                row.append(text)
            else:
                row.append("")
        # 修正赋值顺序,和HTML结构一一对应
        date.append(row[0])
        name.append(row[1])
        number.append(row[2])  

    # 翻页逻辑
    next_btn = driver.find_elements_by_css_selector(".page-next button")
    if next_btn:
        actions = ActionChains(driver)
        actions.move_to_element(next_btn[0]).click().perform()
        time.sleep(4)
    else:
        break
driver.close()

补充说明

你原来的切片[1::2]筛选col-12的逻辑是没问题的,完全符合你给出的HTML结构(带a标签的col-12和带row的col-12交替出现),不需要修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 13:18:01