【问题标题】:Scraping data from a table and storing it in csv file从表中抓取数据并将其存储在 csv 文件中
【发布时间】: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


【解决方案1】:

在每个tr标签中创建变量数据,你可以这样尝试:

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" })
with open('BEPillaiDepart.csv', 'w',newline='') as csvfile:
    f = csv.writer(csvfile)
    f.writerow(['Choice Code', 'Course Name', 'Year of Establishment','Sanctioned Strength'])  # headers
    for x in table:
        table_body = x.find('tbody') #find tbody tag
        rows = table_body.find_all('tr') #find all tr tag
        for tr in rows:
            data=[]
            cols = tr.find_all('td') #find all td tags
            for td in cols:
                data.append(td.text.strip()) 
            f.writerow(data)
            print(data)

【讨论】:

    【解决方案2】:

    如果您搜索 csv 的含义,您会发现它表示逗号分隔值,但是在将文本附加到文件时,我看不到任何逗号。

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多