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

Python嵌套for循环中如何将变量放入双引号字符串作为函数参数

问题原因

  1. BeautifulSoup的CSS选择器中,:contains()的文本参数如果包含空格、特殊字符,必须用引号包裹,你之前的拼接逻辑没有给变量内容加引号,导致解析器识别到非法字符抛出语法错误。
  2. soup.select_one()返回的是单个匹配节点,不是可迭代对象,不能直接用for循环遍历,匹配多个结果可以用soup.select(),匹配单个结果直接判断非空后取值即可。

解决方法

拼接选择器时给变量外层加一层引号即可,四种经典拼接方式修正后的写法如下:

  • format写法:'a:contains("{}")'.format(m)
  • 占位符写法:'a:contains("%s")' % m
  • f-string写法:f'a:contains("{m}")'
  • 字符串拼接写法:'a:contains("' + str(m) + '")'

完整可运行代码

import requests
from bs4 import BeautifulSoup

url = "https://crawler-test.com/"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")

soup.select('div div:nth-child(2) div')

mobile_list = ["Separate Desktop page with separate mobile and/or AMP", 
               "Separate Desktop page with AMP page as AMP and Mobile", 
               "Separate Desktop with different H1",
              "No mobile configuration"]

for m in mobile_list:
    a = soup.select_one(f'a:contains("{m}")')
    if a:
        print(a.text)

运行后即可输出你预期的结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:45:04