detail11detail2detail3< /p>"> Extract text from multiple span elements without classes - using BeautifulSoup-PHP Chinese Network Q&A
Extract text from multiple span elements without classes - using BeautifulSoup
P粉903052556
P粉903052556 2023-09-15 18:03:23
0
2
852

This is what the HTML looks like:

detail1 1 detail2 detail3

I need to extract detail2 and detail3.

But using this code, I can only get detail1.

info = data.find("p", class_ = "details").span.text

How do I extract the required items?

Thanks in advance!

P粉903052556
P粉903052556

reply all (2)
P粉041856955

In your case, select a more specific element, i.e. select all siblingelements of aelement with class number:

soup.select('span.number ~ span')

Example

from bs4 import BeautifulSoup html='''

detail1 1 detail2 detail3

''' soup = BeautifulSoup(html) [t.text for t in soup.select('span.number ~ span')]

Output

['detail2', 'detail3']
    P粉099145710

    You can find alland do a normal index:

    from bs4 import BeautifulSoup html_doc = """\ 

    detail1 1 detail2 detail3

    """ soup = BeautifulSoup(html_doc, "html.parser") spans = soup.find("p", class_="details").find_all("span") for s in spans[-2:]: print(s.text)

    Output result:

    detail2 detail3

    Or use CSS selector:

    spans = soup.select(".details span:nth-last-of-type(-n+2)") for s in spans: print(s.text)

    Output result:

    detail2 detail3
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!