我目前正在嘗試在網站中抓取資料框(關于公司的 sctack 交換),以便在 python 中創建新的資料框。我試圖廢棄資料框的行以便存盤在 csv 檔案中并使用方法 pandas.read_csv()。我遇到了一些麻煩,因為 csv 檔案沒有我想象的那么好。我如何通過網路抓取在 python 中獲得完全相同的資料幀這是我的代碼:
from bs4 import BeautifulSoup
import urllib.request as ur
import csv
import pandas as pd
url_danone = "https://www.boursorama.com/cours/1rPBN/"
our_url = ur.urlopen(url_danone)
soup = BeautifulSoup(our_url, 'html.parser')
with open('danone.csv', 'w') as filee:
for ligne in soup.find_all("table", {"class": "c-table c-table--generic"}):
row = ligne.find("tr", {"class": "c-table__row"}).get_text()
writer = csv.writer(filee)
writer.writerow(row)

uj5u.com熱心網友回復:
請嘗試這個 for 回圈:
rows = []
headers = []
# loop to get the values
for tr in soup.find_all("tr", {"class": "c-table__row"})[13:18]:
row = [td.text.strip() for td in tr.select('td') if td.text.strip()]
rows.append(row)
# get the header
for th in soup.find_all("th", {"class": "c-table__cell c-table__cell--head c-table__cell--dotted c-table__title / u-text-uppercase"}):
head = th.text.strip()
headers.append(head)
這將以您想要的方式獲得您的值和標題。請注意,由于表沒有 id 或任何唯一識別符號,因此您需要適當地穩定您想要考慮所有表的行(參見上面代碼中的 [13:18])。
您可以檢查您的內容,從標題和行中創建一個簡單的資料框,如下所示:
# write csv
df = pd.DataFrame(rows, columns=headers)
print(df.head())
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471073.html
上一篇:下載網頁內容
