【发布时间】:2021-02-03 01:33:01
【问题描述】:
我试图从网站上抓取特定的 div 元素,尽管抓取确实有效。我似乎无法完全锻炼如何将所有指定的元素导出到 CSV 中。当我运行程序时,它会打印出我想要的所有元素,但是当我检查我的 CSV 文件时,它只会导出我正在寻找的元素之一。
对不起,如果这是一个非常菜鸟的问题,并且已经在 StackOverFlow 上寻找了一段时间。
import requests
from bs4 import BeautifulSoup
import csv
#The website im scraping data from
URL = "urlhere"
r = requests.get(URL)
#
soup = BeautifulSoup(r.content, 'html5lib')
#specific elements that I want scraped
staff = soup.findAll("div", class_="col-12 staffListTableRow")
for nums in staff:
staffNums = nums.find_all("div")[3]
print(staffNums)
#Field names and rows for the CSV
fields = ['staff']
rows = [staffNums]
filename = "staff.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
【问题讨论】:
标签: python csv web-scraping