Remove HTML markup (getting the desired text)

Question:

When parsing data from an AJAX table, the data is parsed with the type "bs4.element.Tag" (checked via "type"):
enter image description here

Although I specified the text attribute when requesting:
enter image description here

And I can’t get the text i need inside the HTML markup. As in the screenshot:
enter image description here

For example, the replace/strip e.t.c. function does not work with this type of data :
enter image description here

The class containing the number of comments class_="tcl2".
That is, there is a problem, i can’t delete 2 through re.sub, because the number of comments can be equal to 2 and this 2 remains.
enter image description here

Code:

import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import json
import re
import time

catalog = {}

def parse (): 
    header = {
    'user-agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.167 YaBrowser/22.7.5.940 Yowser/2.5 Safari/537.36"
    } 
    session = requests.Session() 
    retry = Retry(connect=1, backoff_factor=0.5) 
    adapter = HTTPAdapter(max_retries=retry)
    inb = 1
    comp = 'all'
    while inb <= 1:

        url_not_based = (f"http://foodmarkets.ru/firms/filter_result/7/{comp}/0/posted/page{inb}/") 
        session.mount(f'http://foodmarkets.ru/firms/filter_result/7/{comp}/0/posted/page{inb}/'
        ,adapter)
        r = session.get (url_not_based,verify=True,headers=header,timeout=5) 
        soup = BeautifulSoup (r.text, "lxml")
        rounded_block = soup.find_all('tr')

        for round in rounded_block:

            round_сompany = round.find('td',class_='tcl'>'href')
            clear_comp1 = re.sub(r'[a-zA-Z<>/tn=''0-9.:""]','',str(round_сompany))
            clear_comp2 = re.sub(r'[xa0]',' ',clear_comp1)

            round_сity = round.find('td',class_="tc2 nowrap")
            clear_city1 = re.sub(r'[a-zA-Z<>/tn=''0-9.:""]','',str(round_сity))
            clear_city2 = re.sub(r'[xa0]',' ',clear_city1)

            round_сommment = round.find('td',class_="tc2 cntr")
            clear_comm1 = re.sub(r'[a-zA-Z<>""''/tn=.:]','',str( round_сommment))
             
            if round_сompany in catalog:
                continue
            else:
                catalog [round_сompany] = { 
                    "Company": clear_comp2,
                    "City":clear_city2,
                    "Comment": clear_comm1,
                }
        inb = inb+1 
        time.sleep(0.5)

 #   print (catalog)
#with open ("catalog.json","w",encoding='utf-8') as file: 
#    json.dump(catalog, file, indent=4, ensure_ascii=False) 

if __name__ == "__main__":
    parse()
Asked By: Apple

||

Answers:

To get the data from the table to the DataFrame you can use following code:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://foodmarkets.ru/firms/filter_result/7/all/0/posted/page1/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for row in soup.select('tr:has(td.tcl)'):
    tds = [cell.get_text(strip=True, separator=' ') for cell in row.select('td')]
    all_data.append(tds)

df = pd.DataFrame(all_data, columns=['Название компании', 'Города', 'Комментариев', 'Последнее сообщение'])
print(df)

Prints:

                            Название компании           Города Комментариев                           Последнее сообщение
0                              РусКонфета ООО  Санкт-Петербург            0                Сегодня 08:46 от ruskonfeta.ru
1                               "СУББОТА" ООО  Санкт-Петербург            0                       Вчера 14:07 от limon4ik
2   "КАРАБАНОВСКИЙ КОНДИТЕРСКИЙ КОМБИНАТ" ООО           Москва            1                     Вчера 12:13 от kurmanskiy
3                                   Мажор ООО           Москва            0                  30.01.2023 23:11 от bstgroup
4                               ОрионСвит ООО            Минск            0                     16.01.2023 09:28 от Boetc
5                                КД Стайл ООО  Санкт-Петербург            1             11.01.2023 15:00 от kozhemyakinaJ
6                                 БАСТИОН ООО      Владивосток            0                10.01.2023 14:52 от dv_zakupka
7                          ИП Давыдов Р.А. ИП          Саратов            0                 21.12.2022 07:53 от dfkthbz98
8                  Гипермаркет Сити Центр ООО          Назрань            0                   28.11.2022 21:23 от Calibri
9                                     ЭКА ООО        Краснодар            1                        Вчера 08:49 от intense
10         Арсанукаев Бекхан Бадруддинович ИП          Грозный            1                   26.10.2022 08:33 от sale555
11                      ООО "Хлебный Дом" ООО      Симферополь            0               20.10.2022 07:39 от AlexMeganom
12                Горелый Николай Иванович ИП           Брянск            0             18.10.2022 10:20 от Dinastya Vlad
13                         АЛЬЯНС ПРОДУКТ ООО             Орел            1             10.10.2022 12:32 от viola_vrn2017
14              ООО «ТК Русские Традиции» ООО           Москва            1                   25.11.2022 15:34 от ZefirVK
15                           "Технотрейд" ООО            Минск            0                23.09.2022 08:28 от Alejandros
16                           ООО ТК АТЛАС ООО            Киров            0                 15.09.2022 09:47 от Sal291279
17                               Владторг ООО      Владивосток            4             25.01.2023 05:54 от Andrey_Bragin
18    Кондитерская фабрика "Золотая Русь" ООО             Тула            0              30.08.2022 14:48 от ilya_aldagir
19     ООО "Кондитерская фабрика "Финтур" ООО  Санкт-Петербург            1            15.08.2022 11:15 от dvp_wholesaler
20                    Новая Система Услуг ООО           Тамбов            0                       04.08.2022 11:32 от NSU
21              Шидакова И.М. (Ника-Трейд) ИП          Нальчик            1           17.10.2022 12:16 от otdelprodazh.6a
22              Лапин Вячеслав Геннадьевич ИП         Белгород            4                 24.01.2023 13:24 от Anton Bel
23                          ТД Первый Вкус ИП           Москва            5                   18.01.2023 12:34 от pvkioni
24                              ГУДДРИНКС ООО           Москва            0  25.07.2022 12:49 от sergeiaustraliangroup.ru
25                    ООО ГХП Бизнес Гифт ООО           Москва            0                   19.07.2022 14:51 от visss71
26                               Винотека ООО      Севастополь            0              13.07.2022 12:30 от Ooo.vinoteka
27                           Череповецхлеб АО        Череповец            0                06.07.2022 13:54 от Alexcher35
28      Лысанов ИВ(Лысанова ЛБ Мещуров СВ) ИП            Пермь            6             10.11.2022 08:34 от Andrey_Bragin
29                              ХОРЕКА РБ ООО              Уфа            0                  09.06.2022 23:52 от horecarb
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.