Python嵌套for循环中如何将变量放入双引号字符串作为函数参数
问题原因
- BeautifulSoup的CSS选择器中,
:contains()的文本参数如果包含空格、特殊字符,必须用引号包裹,你之前的拼接逻辑没有给变量内容加引号,导致解析器识别到非法字符抛出语法错误。 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
相关产品推荐
相关产品推荐

