【发布时间】:2018-03-03 12:25:49
【问题描述】:
我想从这个网站上抓取数据并以这种方式将其存储在 csv 文件中。
但是当我尝试废弃数据时,它并没有以精确的格式存储。所有数据都存储在第一列本身。我不知道如何解决这个问题。
链接:https://pce.ac.in/students/bachelors-students/
代码:
import csv # file operations
from bs4 import BeautifulSoup as soup # lib for pulling data from html/xmlsites
from urllib.request import urlopen as uReq # lib for sending and rec info over http
Url = 'https://pce.ac.in/students/bachelors-students/'
pageHtml = uReq(Url)
soup = soup(pageHtml,"html.parser") #parse the html
table = soup.find_all("table", { "class" : "tablepress tablepress-id-10 tablepress-responsive-phone" })
f = csv.writer(open('BEPillaiDepart.csv', 'w'))
f.writerow(['Choice Code', 'Course Name', 'Year of Establishment','Sanctioned Strength']) # headers
for x in table:
data=""
table_body = x.find('tbody') #find tbody tag
rows = table_body.find_all('tr') #find all tr tag
for tr in rows:
cols = tr.find_all('td') #find all td tags
for td in cols:
data=data+ "\n"+ td.text.strip()
f.writerow([data])
#print(data)
【问题讨论】:
-
在你的代码中添加 f.writerow(data+"\n")...
标签: python csv web-scraping beautifulsoup