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

VS Code运行Python代码时出现不存在的&符号语法错误求助

问题

在VS Code中运行Python代码时触发语法错误,提示存在&符号,但代码里并没有这个符号。错误信息如下:

& C:/Users/iwanh/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/iwanh/AppData/Local/Programs/Giannis' Programs/bbc_news.py"
  File "<stdin>", line 1
    & C:/Users/iwanh/AppData/Local/Programs/Python/Python310/python.exe"c:/Users/iwanh/AppData/Local/Programs/Giannis' Programs/bbc_news.py" 
    ^
SyntaxError: invalid syntax

但在CMD中执行python.exe bbc_news.py命令时,该文件能正常运行。当前使用Python 3.10.8版本,VS Code已配置同版本。代码如下:

import requests
from bs4 import BeautifulSoup
import pandas as pd

def scrape_bbc_news(url):
    try:
        # 发送GET请求到目标URL
        response = requests.get(url)
        response.raise_for_status()  # 响应状态异常时抛出错误
        
        # 解析HTML内容
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # 初始化存储标题、描述和链接的列表
        headlines = []
        descriptions = []
        links = []
        
        # 收集所有包含标题、描述和链接的容器
        article_containers = []
        
        # 第一种容器类型
        containers_type1 = soup.find_all('div', class_='sc-f98732b0-3 ephYtw')
        article_containers.extend(containers_type1)
        
        for container in article_containers:
            # 检查文章是否包含"live"标识
            live_icon = container.find('svg', class_='sc-3387039d-0 hgdstu sc-1097f7fe-0 jmthjj')
            if live_icon:
                continue  # 跳过带live标识的文章
            
            # 提取标题
            headline = container.find('h2', class_='sc-4fedabc7-3 dsoipF').text.strip()
            headlines.append(headline)
            
            # 提取描述
            description = container.find('p', class_='sc-f98732b0-0 iQbkqW').text.strip()
            descriptions.append(description)
            
            # 提取链接
            link = container.find('a', class_='sc-2e6baa30-0 gILusN')['href'] if container.find('a', class_='gs-c-promo-heading') else ''
            links.append(link)
        
        # 检查标题、描述和链接的数量是否一致
        if len(headlines) != len(descriptions) or len(headlines) != len(links):
            raise ValueError("标题、描述和链接的数量不匹配")
        
        # 将提取的数据转换为DataFrame
        df = pd.DataFrame({
            'headline': headlines,
            'description': descriptions,
            'link': links
        })
        
        return df
        
    except requests.exceptions.RequestException as e:
        print(f"获取数据出错: {e}")
        return None
    except ValueError as ve:
        print(f"值错误: {ve}")
        return None

# 示例调用
url = "https://www.bbc.com/news"
df = scrape_bbc_news(url)

if df is not None:
    print("标题、描述和链接抓取成功:")
    print(df.head())
    df.to_csv('bbc_news_headlines.csv', index=False, encoding='utf-8')
    print("数据已成功保存到 'bbc_news_headlines.csv'。")
else:
    print("抓取数据失败。")
解决方案
  • 问题根源:错误里的&是VS Code运行逻辑出错导致的——它把本该作为系统命令执行的Python启动指令,当成了Python代码片段传入了交互式解释器(<stdin>),而非直接执行。大概率是运行配置错误或使用了不正确的运行方式。
  • 修复步骤:
    1. 用正确方式运行:点击VS Code右上角的"运行Python文件"按钮,或用快捷键Ctrl+F5直接运行,不要在Python交互式窗口里输入运行命令。
    2. 检查launch.json配置:打开.vscode/launch.json,确认program字段指向当前打开的.py文件,配置示例如下:
      {
          "version": "0.2.0",
          "configurations": [
              {
                  "name": "Python: 当前文件",
                  "type": "python",
                  "request": "launch",
                  "program": "${file}",
                  "console": "integratedTerminal"
              }
          ]
      }
      
    3. 切换终端类型:路径里的Giannis' Programs包含单引号,可能导致PowerShell解析异常,可切换到CMD终端:点击终端面板右上角下拉菜单,选择"Command Prompt"。
    4. 重启VS Code:按Ctrl+Shift+P,输入"Reload Window",重新加载窗口后再尝试运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:44:55