作为函数参数,如何将变量放在双引号字符串内?
这是我尝试过的将变量放入引号字符串中的四种经典方法。
k = "boss"
test = 'p:contains({})'.format(k)
print(test, type(test))
test_2 = 'p:contains(%s)' % (k)
print(test, type(test_2))
test_3 = f'p:contains({k})'
print(test, type(test_3))
test_4 = 'p:contains('+str(k)+')'
print(test, type(test_4 ))
给出如下输出。到目前为止,一切顺利。
p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>
问题在这里。我抓取了crawler-test.com;用于测试。
- 我想尝试遍历一个列表。
- 列表中的每个元素都充当select_one函数的参数,如下面的示例。
- 由于某种原因,我尝试了上述四种将变量放入双引号内的方法,我一直得到SelectorSyntaxError "Invalid character">
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:
# This is the tricky part
# I want to put the m inside
for a in soup.select_one('a:contains(m)'):
#for a in soup.select_one('a:contains({})'.format(m)):
#for a in soup.select_one('a:contains(%s)' % m):
#for a in soup.select_one(f'a:contains({m})'):
#for a in soup.select_one('a:contains('+str(m)+')'):
print(a)
如果一切正常,输出应该像
"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"
使用引号…
soup.select_one(f'a:contains("{m}")')