【问题标题】:Need help scraping specific div elements from a website and exporting them into a CSV需要帮助从网站上抓取特定的 div 元素并将它们导出为 CSV
【发布时间】: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


    【解决方案1】:

    我建议您重组代码,以便一次将每一行写入文件。类似于以下内容:

    import requests
    from bs4 import BeautifulSoup
    import csv
    
    filename = "staff.csv"
    #The website I'm scraping data from
    URL = "urlhere"
    r = requests.get(URL)
    soup = BeautifulSoup(r.content, 'html5lib')
    
    # writing to csv file
    with open(filename, 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(['staff'])   # write the header
    
        staff = soup.findAll("div", class_="col-12 staffListTableRow")
    
        for nums in staff:
            staffNums = nums.find_all("div")[3].text
            print(staffNums)
            csvwriter.writerow([staffNums])
    

    显然这还没有经过测试,因为没有可以测试的 URL,但它应该为您提供不同的尝试方法。

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2021-10-07
      相关资源
      最近更新 更多