1 回答

TA貢獻1802條經驗 獲得超5個贊
我創建了 2 個數組來存儲 2 種不同類型的抓取數據。 pandas.DataFrame()將創建一個數據框對象并將pandas.to_csv()數據框對象發送到 .csv 文件。
這可能不是最有效的代碼,但它可以工作
import requests
from bs4 import BeautifulSoup
import pandas as pd
URL = 'https://mychesterfieldschools.com/mams/news-and-announcements/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find_all('div', class_='col-sm-12 col-md-12')
// declaring the 2 arrays for storing your scraped data
text = []
a_tags = []
for results in results:
? ? body = results.find('p')
? ? link = results.find('a')
? ? a = body.text
? ? b = link
? ? print(a)? ? ? ? // prints the text (data type string)
? ? print(b)? ? ? ? // prints the tag (data type bs4.element.Tag object)
? ? // store the text in text array
? ? text.append(a)
? ? // convert the tags to string and store in a_tags array
? ? a_tags.append(str(b))
// prints the saved arrays
print("text :? ? ", text)
print("tags :? ? ", a_tags)
// creates a pandas dataframe object of the above 2 arrays
df = pd.DataFrame(
? ? {
? ? ? ? "Text": text,
? ? ? ? "A_tags": a_tags
? ? }
)
// converts to csv
df.to_csv("data.csv", index=False, encoding="utf-8")
輸出data.csv
文件出現在與 python 腳本相同的目錄中。
這是 csv 在 Microsoft Office Excel 上的顯示方式:
添加回答
舉報