You need to enable JavaScript to run this app. Python爬取网页数据时如何自动将提取内容以逗号分隔格式输出
优惠活动
大模型
产品
解决方案
定价
更多

Python爬取网页数据时如何自动将提取内容以逗号分隔格式输出

问题根因

当前代码在循环体内对每个匹配到的数字单独执行print()调用,Python默认每次print会自动附带换行符,因此最终输出为逐行排列的独立内容,无法形成要求的逗号拼接连续字符串格式。

实现逻辑调整
  • 新建空列表存储所有提取到的数字
  • 循环遍历页面元素时,将匹配到的数字追加到列表中,不直接在循环内做打印
  • 全部元素遍历完成后,使用,.join()`方法将列表内元素拼接为单条字符串,再执行一次性打印输出
修改后的完整可运行代码
from selenium import webdriver
from bs4 import BeautifulSoup
import re

# 修正Windows路径转义隐患,使用原始字符串避免路径识别异常
path = r'C:\chromedriver'
options = webdriver.ChromeOptions()
options.add_argument("--mute-audio")
options.add_argument("--headless")
driver = webdriver.Chrome(path, options=options)

driver.get('website')
soup = BeautifulSoup(driver.page_source, 'html.parser')
items = soup.find('div', {'class': 'mix_container'})

extracted_id_list = []
for item in items.find_all('div', {'data-ref': 'item'}):
    match_res = re.search('\d+', item.find('a')['href'])
    # 增加匹配判断,避免无匹配内容时报错中断
    if match_res:
        extracted_id_list.append(match_res.group())

# 按要求用逗号拼接后输出
print(','.join(extracted_id_list))

# 任务完成后关闭浏览器进程,释放系统资源
driver.quit()
输出效果

运行代码后将得到无换行、以逗号分隔的连续数字字符串,和预期格式一致:

283049610,5785985,93709266

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 01:36:01