Home>

I want to get the same result as assigning a variable and writing it directly in a function.

Currently, I am writing programming to get necessary information from url using bs4.
I was able to get the information I wanted using find_all, but I created a variable so that I could get it with other URL and tag combinations.
However, when I used the created variable as an argument of find_all, I could not get any information.
Is there any difference between writing directly in the argument and using a variable?
I would appreciate it if you could tell me.
Thank you.

Corresponding source code
from bs4 import BeautifulSoup
import requests
home_url = "https://stackoverflow.com/"
html = requests.get (home_url)
home_tag_info = "class_ = \" P-fvRegist__messageBox \ ""
soup = BeautifulSoup (html.text,'html.parser')
for tag in soup.find_all (class_=" searchResults_name"):
# Does not work below
# for tag in soup.find_all (home_tag_info):
    print (tag.text)
Supplementary information (FW/tool version, etc.)

Windows10 Home
Python 3.9.0
Visual Studio Code

  • Answer # 1

    Specify optional argumentsclass_ =Do not set to a variable.

    -home_tag_info = "class_ = \" P-fvRegist__messageBox \ ""
    + home_tag_info = "P-fvRegist__messageBox"
    -for tag in soup.find_all (class_=" searchResults_name"):
    -# Does not work below
    -# for tag in soup.find_all (home_tag_info):
    + for tag in soup.find_all (class_ = home_tag_info):

  • Answer # 2

    home_tag_info = "P-fvRegist__messageBox \"
    soup = BeautifulSoup (html.text,'html.parser')
    for tag in soup.find_all (class_ = home_tag_info):
        print (tag.text)

  • Answer # 3

    soup.find_all (class_="searchResults_name")
    # In this case, for the option name class_ as an argument
    It means that the element # [searchResults_name] is specified.
    soup.find_all ("class_ = \" P-fvRegist__messageBox \ "")
    # In this case, I did not specify any options as arguments.
    # I'm just giving the string [class_=" P-fvRegist__messageBox"].

  • Answer # 4

    I was able to organize my knowledge because I used it without noticing that it was an optional argument.
    Thank you for telling me.