简体   繁体   中英

How to get text in span tag with beautifulsoup and python

I am using beautifulsoup with html5lib to try to get the number after QTY: and I have tried many unsuccessful methods.

This is the span tag format:

  <span id="ctl00_cph1_grdRfqSearch_ctl45_lblPr">0080970139<br>QTY: 255</span>

This is the code that produces the span tag:

  PreQty = container1.find(id="ctl00_cph1_grdRfqSearch_ctl03_lblPr")                            

I have tried adding .text, .get_text() and others but they don't work

How could I get the value after QTY: ?

I just need the next step to get the text out of the span tag

     <span id="ctl00_cph1_grdRfqSearch_ctl45_lblPr">0080970139<br>QTY: 255</span>

.select() returns a list of matching elements . So if your selector matches any elements, you will first need to retrieve the element from the array, and then you can access it's .text attribute.

To demonstrate, you could do something like:

for element in PreQty:
    print(element.text)

You can try this, the tricky part here is to find the "QTY" after the <br> tag.

from bs4 import BeautifulSoup

text = """<span id="ctl00_cph1_grdRfqSearch_ctl45_lblPr">0080970139<br>QTY: 255</span>"""
soup = BeautifulSoup(text,'html.parser')
QTY = soup.find("span", id = "ctl00_cph1_grdRfqSearch_ctl45_lblPr" ).find('br').next_sibling
print(QTY)

#outputs 
QTY: 255

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM