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。
添加回答
舉報