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

Python爬虫for循环中如何在每部电影数据末尾追加空串分隔

代码修改方案

问题根源

  1. 原有代码将空字符串追加逻辑放在了<td>遍历循环内部,导致每提取一个字段就插入一个空串,需要将该逻辑移到单个电影页面所有数据提取完成之后执行
  2. 原有testone初始化放在了页面循环内部,每次遍历新页面都会清空之前的存储数据,需要把初始化提到循环外部

修改后完整代码

import requests
from bs4 import BeautifulSoup

test = ['https://www.latlong.net/location/10-things-i-hate-about-you-locations-250',
 'https://www.latlong.net/location/12-angry-men-locations-818',
 'https://www.latlong.net/location/12-monkeys-locations-501']

# 存储全局数据的字典放在循环外初始化
testone = {'location name':[],'film':[]}

for url in test:
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')
    # 提取当前页面所有地点、经纬度数据
    for th in soup.select("td"):
        testone['location name'].append(th.text.strip())
    # 单页所有数据提取完成后,追加一个空字符串作为分隔符
    testone['location name'].append('')
    # 提取当前页面的电影名称
    film_name = soup.select_one("h3").text.strip()
    testone['film'].append(film_name)

补充说明

如果不需要最后一部电影末尾的空分隔符,可以在所有页面遍历完成后执行testone['location name'].pop()移除最后一个空串即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:15:02