Home > Mobile >  Put a variable inside double quoted string, but as function parameter in a nested for loop
Put a variable inside double quoted string, but as function parameter in a nested for loop

Time:09-24

As a function parameter, How can I put a variable inside double-quoted string?

These are the four classic ways of putting a variable inside a quoted string that I have tried.

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 ))

which gives me the following output. So far, so good.

p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>
p:contains(boss) <class 'str'>

Here is the problem. I grabbed "crawler-test.com" for the test purpose.

  1. What I want is to try to iterate through a list.
  2. Each element from the list acts like a parameter of select_one function like the below example.
  3. For some reason, I tried the above four ways of putting a variable inside the double quotes, I keep getting 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)

If everything went well, the output should be like

"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"

CodePudding user response:

just use quotes...

soup.select_one(f'a:contains("{m}")')
  • Related