问题描述:

已经将所需网页保存到本地了(大概有60G的网页数据),需要提取网页上表格数据(网页上表格样式不一样表格位置也不一定内容也不一样表格没有id与class,只有table的父节点dividclass
image.png

思路:

1. read_html( )

查询到pandas的read_html( )方法可以获取网页上表格数据,如:
其中read_htm方法参数为:https://www.cnblogs.com/litufu/articles/8721207.html

  1. # jupyter notebook
  2. import pandas as pd
  3. tables = pd.read_html('D:\\rexel数据\\HTML\\AVN300.html')
  4. print("table数量:",len(tables))
  5. df=tables[0]
  6. df

image.png
以上方法只能获取到该网页上所有表格,如果想要获取指定表格需要使用matchattr参数:

  • match参数里面的内容需要是表格里面含有的字符,如表格中含有“经典荧光款”,但该批量网页上表格内容未知,无法使用match参数 ```python import pandas as pd tables = pd.read_html(‘D:\rexel数据\HTML\AVN300.html’,match=’经典荧光款’) print(“table数量:”,len(tables)) df=tables[0] df
  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/1283987/1635930024232-e8ac0c52-e13d-4559-8729-e189c8e21498.png#clientId=u3331c778-3d00-4&from=paste&height=328&id=u21032e33&margin=%5Bobject%20Object%5D&name=image.png&originHeight=436&originWidth=422&originalType=binary&ratio=1&size=20568&status=done&style=none&taskId=u6e96d7e2-1a2e-47d6-9a7a-5b296b1dc55&width=317)
  2. - **attrs:**dict None, 可选参数
  3. 这是属性的词典,您可以传递该属性以用于标识HTML中的表。该参数传递的是表格的idclass等属性,但该表格无这些属性值,也无法使用!
  4. ```python
  5. attrs = {'id': 'table-1'}

这就放弃了吗?不…请看下面方法

2. BeautifulSoup+read_html

经过上述方法无法定位到指定div下面的表格,查询到使用BeautifulSoup可以定位到指定格:

with open('D:\\rexel数据\\HTML\\CWL044.html', 'rb') as f:
    content = f.read().decode('utf-8')
    page = BeautifulSoup(content, 'html.parser')
    table_5 = page.find('div', id="tec5").find_all('table')
    print(table_5)

table_5 = page.find('div', id="tec5").find_all('table'):找到id=”tec5”的div下面的所有表格,打印table_5:

[
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>轴承形式记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-indent: 2em;">7:单列角接触球轴承</p></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>尺寸系列记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-indent: 2em;">标准系列  9:19系列   0<span style="font-family: 微软雅黑, ">:</span>10系列   2:02系列</p></td></tr></tbody></table>, <table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>内径代号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><ul class="list-paddingleft-2" style="list-style-type: disc;"><li><p>03以下  轴承内径    00<span style="font-family: 微软雅黑, ">:</span>10mm   01<span style="font-family: 微软雅黑, ">:</span>12mm   02<span style="font-family: 微软雅黑, ">:</span>15mm   03<span style="font-family: 微软雅黑, ">:</span>17mm</p></li><li><p>04以上  轴承内径    内径记号*5(mm)</p></li></ul></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>接触角记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-indent: 2em;">C:15°     A5<span style="font-family: 微软雅黑, ">:25°     A<span style="font-family: 微软雅黑, ">:30°<span 13px;="" 26px;"="" font-size:="" microsoft="" style="font-family: 微软雅黑, " text-indent:="" yahei";="">     B</span><span 13px;="" 26px;"="" font-size:="" microsoft="" style="font-family: 微软雅黑, " text-indent:="" yahei";="">:40°</span></span></span></p></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td colspan="2" rowspan="1" style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>材料记号</strong></span></p></td></tr><tr><td colspan="2" rowspan="1" style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top"><ul class="list-paddingleft-2"><li><p style="line-height: 1.5em;">无记号:钢球(SUJ2)</p></li><li><p style="line-height: 1.5em;">SN24:陶瓷球             </p><p><img alt="选型-1.jpg" src="https://image-c.ehsy.com/uploadfile/opc/editor/image/wm/fKk3wd957yX1uo1kULz3B45FB1KLUCoM1exKN9SvluQ%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D" style="float: right;" title="fKk3wd957yX1uo1kULz3B45FB1KLUCoM1exKN9SvluQ%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D"/></p></li></ul><p style="line-height: 1.5em;"><br/></p></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>保持架记号</strong></span></p></td></tr><tr><td style="border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-align:center"><img alt="选型-2.jpg" height="262" src="https://image-c.ehsy.com/uploadfile/opc/editor/image/wm/fKk3wd957yX1uo1kULz3B4ElfUuOfFqy%2FC9SPbeUIEU%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D" style="width: 700px; height: 262px;" title="fKk3wd957yX1uo1kULz3B4ElfUuOfFqy%2FC9SPbeUIEU%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D" width="700"/></p></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>密封圈记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><ul class="list-paddingleft-2" style="list-style-type: disc;"><li><p style="line-height: 1.5em;">无记号:开放式</p></li><li><p style="line-height: 1.5em;">V1N:非接触橡胶密封圈(能够防止外部异物侵入,防止润滑脂飞散,实现高信赖性和润滑脂长寿命化)</p></li></ul></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>组合记号</strong></span></p></td></tr><tr><td style="border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-align:center"><img alt="选型-3.jpg" src="https://image-c.ehsy.com/uploadfile/opc/editor/image/wm/fKk3wd957yX1uo1kULz3B8GZzHfRIdtAMaoueQExuAc%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D" title="fKk3wd957yX1uo1kULz3B8GZzHfRIdtAMaoueQExuAc%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D"/></p></td></tr></tbody></table>, 
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>预紧记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><ul class="list-paddingleft-2" style="list-style-type: disc;"><li><p style="line-height: 1.5em;">EL:微预紧            <span style="font-family: 微软雅黑, ">L:轻预紧             <span style="font-family: 微软雅黑, ">M:中预紧<span style="font-family: 微软雅黑, ">             </span><span style="font-family: 微软雅黑, ">H:重预紧</span> </span></span></p></li><li><p style="line-height: 1.5em;">CP:特殊预紧游隙                              CA:特殊轴向游隙</p></li></ul></td></tr></tbody></table>,
<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>精度记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-align:center"><img alt="选型-4.jpg" src="https://image-c.ehsy.com/uploadfile/opc/editor/image/wm/fKk3wd957yX1uo1kULz3B8iCghVynNVY%2BSOykLTJ%2FI0%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D" title="fKk3wd957yX1uo1kULz3B8iCghVynNVY%2BSOykLTJ%2FI0%3D%3AaWg0OHRzZGxnUFBZU2FBUg%3D%3D"/></p></td></tr></tbody></table>
]

read_html( )方法课题传递 网址、文件、字符串,这时只需要遍历上述list将每一行的表格字符串(read_html()传入的是网址、文件、字符串,需要将上面list转为字符串,str(list))传递给read_html( ),就可以获得表格数据

import pandas as pd

table_1 = '<table width="100%"><tbody><tr class="firstRow"><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="line-height: 1.5em;"><span style="font-size: 14px;"><strong>轴承形式记号</strong></span></p></td></tr><tr><td style="word-break: break-all; border-color: rgb(89, 89, 89);" valign="top" width="783"><p style="text-indent: 2em;">7:单列角接触球轴承</p></td></tr></tbody></table>'

tables = pd.read_html(table_1)
tables[0]

image.png

完整代码:

import pandas as pd
from bs4 import BeautifulSoup

if __name__ == '__main__':

    with open('D:\\rexel数据\\HTML\\CWL044.html', 'rb') as f:
        content = f.read().decode('utf-8')
        page = BeautifulSoup(content, 'html.parser')
        table_5 = page.find('div', id="tec5").find_all('table')
        # read_html()传入的是网址、文件、字符串,需要将上面list转为字符串,str(list)
        for table in table_5:
            df = pd.read_html(str(table))
            print(df[0])    # df[0]是dataframe,df是一个list

image.png

如何保存表格数据?

可以将dataframe转为字典存储:to_dict()
to_dict方法参数讲解:https://blog.csdn.net/m0_37804518/article/details/78444110

# df[0]是一个dataframe,如果写df是一个list
dic = df[0].to_dict(orient='list')

完整代码:

import pandas as pd
from bs4 import BeautifulSoup

if __name__ == '__main__':

    with open('D:\\rexel数据\\HTML\\CWL044.html', 'rb') as f:
        content = f.read().decode('utf-8')
        page = BeautifulSoup(content, 'html.parser')
        table_5 = page.find('div', id="tec5").find_all('table')
        # read_html()传入的是网址、文件、字符串,需要将上面list转为字符串,str(list)
        for table in table_5:
            df = pd.read_html(str(table))
            # dataframe转字典
            dic = df[0].to_dict(orient='list')
            print(dic)

dataframe:
image.png
转为字典:

{0: ['尺寸系列记号', '标准系列 9:19系列 0:10系列 2:02系列']}