【问题标题】:Writing scraped data in rows with python使用python将抓取的数据写入行中
【发布时间】:2020-11-19 04:17:12
【问题描述】:

我有一个基本的 bs4 网络爬虫,获取我的爬取数据没有问题,但是当我尝试将其写入 .csv 文件时,我遇到了一些问题。我无法将数据写入多个列。在the tutorial 我有点关注,他可以很容易地用“,”分隔行,但是当我用 excel 打开我的 CSV 时,无论是在标题中还是在数据中都没有分隔符,我错过了什么?

import requests
from bs4 import BeautifulSoup

url="myurl"

page=requests.get(url)

soup=BeautifulSoup(page.content,'html.parser')

items=soup.find_all('a', class_='listing-card')

filename = 'data.csv'
f = open(filename, "w")
header = "name, price\n"
f.write(header)

for item in items:
    title = item.find('span', class_='title').text
    price = item.find('span', class_='price').text
    f.write(title.replace(",","|") + ',' + price + "\n")

f.close()

【问题讨论】:

  • 当您在文本编辑器中打开文件时,data.csv 的外观如何?

标签: python dataframe csv web-scraping beautifulsoup


【解决方案1】:

我发现将数据放入 CSV 文件的最简单方法是将数据放入 pandas DataFrame,然后使用 to_csv 方法写入文件。

使用您的示例,代码如下:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url="myurl"

page=requests.get(url)

soup=BeautifulSoup(page.content,'html.parser')

items=soup.find_all('a', class_='listing-card')

filename = 'data.csv'
f = open(filename, "w")
header = "name, price\n"
f.write(header)

#
# Create an empty list to store entries
mylist = []
for item in items:
    title = item.find('span', class_='title').text
    price = item.find('span', class_='price').text
    #
    # Create the dictionary item to be appended to the list
    entry = {'name' : title, 'price' : price}
    mylist.append(entry)
    
myDataframe =  pd.DataFrame(mylist) 
myDataframe.to_csv('CSV_file.csv')   

【讨论】:

    【解决方案2】:

    另一种方法。

    from simplified_scrapy import SimplifiedDoc, utils, req
    url = "myurl"
    html = req.get(url)
    
    rows = []
    rows.append(['name', 'price'])  # Add header
    
    doc = SimplifiedDoc(html)
    items = doc.getElements('a', attr='class', value='listing-card') # Get all nodes a according to the class
    for item in items:
        title = item.getElement('span', value='title').text
        price = item.getElement('span', value='price').text
        rows.append([title, price])
    
    utils.save2csv('data.csv', rows) # Save to CSV file
    

    这里有更多示例:https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-06
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多