[Python] Beautiful Soup; splitting a paragraph only by <br> where stripped_strings is not...

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm rather new to using Beautiful Soup and I'm having some issues splitting some html correctly by only looking at html breaks and ignoring other html elements such as changes in font color etc.

    The code is running through a page looking for all sections of blockquote with each blockquote section containing one or multiple lines of text similar to the following:

    <blockquote>
    <p>RT CLOAK<a href="https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesc3.htm#1057"><img src="./British Museum Object Names Theasarus_ Terms AB-AM_files/link.gif" border="0"></a><br><font color="FFFFFF">RT </font>COAT<a href="https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesc4.htm#1082"><img src="./British Museum Object Names Theasarus_ Terms AB-AM_files/link.gif" border="0"></a><br>BT GARMENT<a href="https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesg1.htm#2099"><img src="./British Museum Object Names Theasarus_ Terms AB-AM_files/link.gif" border="0"></a><br><i>NP ABBA</i><a href="https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesa1.htm#3"><img src="./British Museum Object Names Theasarus_ Terms AB-AM_files/link.gif" border="0"></a></p>
    <hr width="90%"></blockquote>
    <p><a name="3"></a><i>ABBA NP</i></p>
    <blockquote>


    when using the stripped_strings function within Beautiful Soup I am getting very close to what I am looking for however it seems to be splitting this section:

    <font color="FFFFFF">RT </font>COAT<a href="https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesc4.htm#1082"><img src="./British Museum Object Names Theasarus_ Terms AB-AM_files/link.gif" border="0"></a>


    into two rows of data in my list giveing my an output like this: 2 ABAYAH RT CLOAK 2 ABAYAH RT 2 ABAYAH COAT 2 ABAYAH BT GARMENT 2 ABAYAH NP ABBA

    How do I solely split by the breaks so that I get the result as follows: 2 ABAYAH RT CLOAK 2 ABAYAH RT COAT 2 ABAYAH BT GARMENT 2 ABAYAH NP ABBA

    The code I have at the moment is as follows:

    from bs4 import BeautifulSoup
    import requests

    pages = ['https://terminology.collectionstrust.org.uk/British-Museum-objects/Obthesa1.htm']

    b = 1

    for bp in pages:

    response = requests.get(bp)
    html = response.text

    soup = BeautifulSoup(html, "lxml")

    y = soup.find_all('blockquote')
    for x in y:
    z = x.find_previous('p')
    for l in x.stripped_strings:
    print(b, z.text, l)
    b = b+1

    Continue reading...

Compartilhe esta Página