Python Forum
Trying to extract style attribute with BeautifulSoup
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to extract style attribute with BeautifulSoup
#1
Hello all,

In practising some simple web scraping using Requests and BeautifulSoup, I've come across a challenge I haven't tried before and after several attempts that are getting me nowhere, I thought I'd reach out for some direction please.

With this html:
<span class="bv-rating-stars-container">
<span aria-hidden="true" class="bv-rating-stars bv-rating-stars-off"> ★★★★★ </span>
<span aria-hidden="true" class="bv-rating-stars-on bv-rating-stars" style="width: 97%;"> ★★★★★ </span>
</span>

I'm wanting to get the 'star rating' for this product, which is contained in the 'style' tag. So I'm trying to extract the "width: 97%". I was thinking once I'm able to get the "width: 97%", I should be able to use Regex to extract the 97% part (which I think I would be able to do myself), but I'm stuck on being able to extract the "width: 97%" component.

My last attempt was:
rbc = ratingclass.find('span', class_='bv-rating-stars-container')
        rating= rbc.find('span')['style']
and I get an error of:
Error:
[error]Traceback (most recent call last): File "C:\Users\PycharmProjects\test.py", line 95, in <module> rating= rbc.find('span')['style'] File "C:\Users\PycharmProjects\mytest\venv\lib\site-packages\bs4\element.py", line 1519, in __getitem__ return self.attrs[key] KeyError: 'style'
[/error]

Happy to provide more of the code to get to this point if required, I just thought it may be irrelevant to the challenge.

Thank you for your assistance.
Reply
#2
After more trying, I resolved it.

rbs = rbc.find('span', class_ = 'bv-rating-stars-on bv-rating-stars')
        rating = rbs['style']
        print(rating)
Output:
width: 97%;
Thank you for reading.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python 3.9 : BeautifulSoup: 'NoneType' object has no attribute 'text' fudgemasterultra 1 8,945 Mar-03-2021, 09:40 AM
Last Post: Larz60+
  BeautifulSoup attribute problem zzy 3 3,046 Dec-07-2020, 11:07 PM
Last Post: zzy
  Extract data with Selenium and BeautifulSoup nestor 3 3,937 Jun-06-2020, 01:34 AM
Last Post: Larz60+
  BeautifulSoup 'NoneType' object has no attribute 'text' bmccollum 9 14,696 Sep-14-2018, 12:56 PM
Last Post: bmccollum
  BeautifulSoup - extract table but not using ID jonesin1974 5 29,185 Apr-27-2018, 07:22 PM
Last Post: NinoBaus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020