Как импортировать теги, id и текст из HTML в таблицу?
import bs4
import pandas as pd
url_code = '''
<div class="tabledata">
<table>
<caption>
<big>type1</big>
</caption>
<tr>
<select>
<option value="101">o1</option>
<option value="102">o2</option>
</select>
</tr>
<tr id="101_1">
<td>1</td>
<td>Test1(1)</td>
</tr>
<tr id="101_2">
<td>2</td>
<td>Test1(2)</td>
</tr>
<tr id="102_1">
<td>3</td>
<td>Test2(1)</td>
<tr id="102_2">
<td>4</td>
<td>Test2(2)</td>
</tr>
</table>
</div>
'''
soup = bs4.BeautifulSoup(url_code, 'html.parser')
table = soup.select_one('.tabledata')
#Создаем каждый столбец
values = [tag['value'] for tag in soup.select('option[value]')]
ids = [tag['id'] for tag in soup.select('tr[id]')]
tds = soup.find_all('td')
#Создаем список строк
currencies = []
for i in range(0, len(tds)):
row = [values[i].get_text(),
ids[i].get_text(),
tds[i].get_text()]
currencies.append(row)
#import to xlsx
df = pd.DataFrame(currencies,
columns=['values','ids','tds'])
df.to_excel('out.xlsx', index=False)
Как сохранить данные в таблицу в таком виде:
value ids tds
o1 101_1 Test1(1)
o1 101_2 Test1(2)
o2 102_1 Test2(1)
o2 102_2 Test2(2)
Или в таком виде:
ids tds
101_1 Test1(1)
101_2 Test1(2)
102_1 Test2(1)
102_2 Test2(2)
Ответы (1 шт):
Автор решения: ganz
→ Ссылка
Изменил исходный код работая вставляя теги при помощи bs4 которые при парсинге станут столбцами.
import bs4
import pandas
url_code = '''
<html><head></head><body>
<div class="tabledata">
<table>
<caption>
<big>type1</big>
</caption>
<tr>
<select>
<option value="101">o1</option>
<option value="102">o2</option>
</select>
</tr>
<tr id="101_1">
<td>1</td>
<td>Test1(1)</td>
</tr>
<tr id="101_2">
<td>2</td>
<td>Test1(2)</td>
</tr>
<tr id="102_1">
<td>3</td>
<td>Test2(1)</td>
<tr id="102_2">
<td>4</td>
<td>Test2(2)</td>
</tr>
</table>
</div>
</body></html>'''
#########изменяем хтмл для парсинга
soup = bs4.BeautifulSoup(url_code, 'lxml')
r=soup.find('select').children
seldict={}
for it in r:
if it.string==None or it.string=='\n':
continue
seldict[str(it.attrs['value'])]=str(it.string)
print(seldict)
r=soup.find('table').children
for it in r:
if not isinstance(it,bs4.element.Tag):
continue
if it.name != 'tr' or not it.has_attr('id'):
continue
tag=soup.new_tag("td")
tag.string=it.attrs['id']
it.insert(0,tag)
rem=it.attrs['id'][:it.attrs['id'].find('_')]
tag=soup.new_tag("td")
tag.string=seldict[rem]
it.insert(0,tag)
#парсим
df=pandas.read_html(str(soup))
df = df[0].dropna(axis=0, thresh=4)
#приводим вв нужный вид
df=df.drop(['Unnamed: 2'],axis=1)
df=df.rename({'Unnamed: 1':'ids','Unnamed: 0':'value','Unnamed: 3':'tds'},axis=1)
print(df)
'''
value ids tds
0 o1 101_1 Test1(1)
1 o1 101_2 Test1(2)
2 o2 102_1 Test2(1)
3 o2 102_2 Test2(2)
'''
df.to_excel('out.xlsx', index=False)
