I have a "problem" with BeautifulSoup and more especially with re module Here is the problem:
import re
from bs4 import BeautifulSoup
string = """
<div id="my_id">
<ul>
<li>something</li>
<li class="color12">something</li>
<li class="color45">something else</li>
</ul>
</div>
"""
soup = BeautifulSoup(string)
li = soup.find_all('li', {'class': re.compile('color(\d+)')} )
for ele in li:
print ele['class'] # will print colorXXXX but i would like to know how to get only this XXXX
But i would like to extract only the number after color. Is it possible or do I have the obligation to use something like :
match = re.search(r'color(\d+)', str(ele['class']))
if match:
print match.group(1)
Thank you for helping :)
You'll have to re-apply the regular expression. Just store it in variable and reuse:
colorpattern = re.compile(r'color(\d+)')
li = soup.find_all('li', {'class': colorpattern} )
for ele in li:
print colorpattern.search(ele['class']).group(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With