1 回答

TA贡献1829条经验 获得超4个赞
没有更多信息,我想这会对您有所帮助:
from bs4 import BeautifulSoup
import pandas as pd
html = '''<div id="mydiv">
<table>
<tr>
<td>header 1</td>
<td>value 1</td>
</tr>
<tr>
<td>header 2</td>
<td>value 2</td>
</tr>
<tr>
<td>header 3</td>
<td>value 3</td>
</tr>
</table>
</div>'''
num = 0
headers = []
values = []
rows = []
while True:
soup = BeautifulSoup(html, 'html.parser')
trs = soup.select('div#mydiv tr')
for t in trs:
for header, value in zip(t.select('td')[0], t.select('td')[1]):
if num == 0:
headers.append(header)
values.append(value)
rows.append(values)
values = []
num += 1
if num > 50:
break
df = pd.DataFrame(rows, columns= headers)
print(df.head())
df.to_csv('mycsv.csv')
印刷:
header 1 header 2 header 3
0 value 1 value 2 value 3
1 value 1 value 2 value 3
2 value 1 value 2 value 3
3 value 1 value 2 value 3
4 value 1 value 2 value 3
依此类推...并将数据保存到名为mycsv.csv.
csv 文件前 30 行
在此代码中,我在您的示例 html 代码上运行了 50 次循环,以生成更多的数据值。但是你需要为每一页提出一个新的请求并对其进行补充,但我想你明白了。这只是您如何编写代码的 POC。
添加回答
举报