pythonweb-scrapingbeautifulsoupdata-extraction

How to extract <td> elements with no attributes?


I am a newbie in web scraping and I have been stuck with some issue. I tried and searched but nothing at all. I want to extract data from the table. The problem is that tr and td elements don't have attributes, just class. <td class="review-value"> is the same for different values. I don't know how to separate them. I need lists with every single value for example:

list_1 = [aircraft1, aircraft2, aircraft3, ..]
list_2 = [type_of_traveller1, type_of_traveller2, ...]
list_3 = [cabin_flown1, cabin_flown2,...]
list_4 = [route1, route2,...]
list_5 = [date_flown1, date_flown2, ..]

This is the table code:

<table class="review-ratings">
  <tr>
    <td class="review-rating-header aircraft">Aircraft</td>
    <td class="review-value">Boeing 787-9</td>
  </tr>
  <tr>
    <td class="review-rating-header type_of_traveller">Type Of Traveller</td>
    <td class="review-value">Couple Leisure</td>
  </tr>
  <tr>
    <td class="review-rating-header cabin_flown">Seat Type</td>
    <td class="review-value">Business Class</td>
  </tr>
  <tr>
    <td class="review-rating-header route">Route</td>
    <td class="review-value">Mexico City to London</td>
  </tr>
  <tr>
    <td class="review-rating-header date_flown">Date Flown</td>
    <td class="review-value">February 2023</td>
  </tr>
</table>

I am using BeautifulSoup:

page = requests.get(url)
table = soup.find('article')
review_table = table.find_all('table', class_ = 'review-  ratings')
find_tr_header = table.find_all('td', class_ = 'review-rating-header')
headers = []
for i in find_tr_header:
     headers.append(i.text.strip())

And I don't know what to do with class="review-value".


Solution

  • As I can see in your table each field has a cell .review-value that is following it (direct sibling).

    So what you can do is use the selector + in CSS. For instance .aircraft + .review-value will give you the value of the aircraft.

    In Beautiful Soup you can even avoid this type of selector since there are built-in methods available for you. Check next-sibling