【问题标题】:How to write csv and insert scrape data如何编写csv并插入抓取数据
【发布时间】:2019-08-16 14:30:09
【问题描述】:

我正在为我的研究设计 scrape 项目,但我坚持在 csv 中写入 scrape 数据。请帮帮我?

我已成功抓取数据,但我想将其存储在 csv 中,下面是我的代码

需要编写代码从网站中提取所有 html,然后将其保存到 csv 文件中。

我认为我需要以某种方式将链接转换为列表,然后编写列表,但我不确定该怎么做。

这是我目前所拥有的:

import requests
import time
from bs4 import BeautifulSoup
import csv



# Collect and parse first page
page = requests.get('https://www.myamcat.com/jobs')
soup = BeautifulSoup(page.content, 'lxml')

print("Wait Scraper is working on ")
time.sleep(10)
if(page.status_code != 200):
    
    print("Error in Scraping check the url")
else:
    
    print("Successfully scrape the data")
    time.sleep(10)
    print("Loading data in csv")
    file = csv.writer(open('dataminer.csv', 'w'))
    file.writerow(['ProfileName', 'CompanyName', 'Salary', 'Job', 'Location']) 
       
    for pname in soup.find_all(class_="profile-name"):
        
        #print(pname.text)
        profname = pname.text
        file.writerow([profname, ])
        
    for cname in soup.find_all(class_="company_name"):

        print(cname.text)
                   
    for salary in soup.find_all(class_="salary"):

        print(salary.text)
                 

    for lpa in soup.find_all(class_="jobText"):

        print(lpa.text) 

    for loc in soup.find_all(class_="location"):

        print(loc.text)

        

            



【问题讨论】:

  • 首先,使用.append() 将结果保存在列表中。然后保存到csv 文件中。参考这个thread
  • 我是新手,你能告诉我怎么做吗?

标签: python csv web-scraping beautifulsoup


【解决方案1】:

制作一个字典并将数据保存到其中然后保存到csv,检查下面的代码!

import requests
import time
from bs4 import BeautifulSoup
import csv



# Collect and parse first page
page = requests.get('https://www.myamcat.com/jobs')
soup = BeautifulSoup(page.content, 'lxml')
data = []
print("Wait Scrapper is working on ")
if(page.status_code != 200):
    print("Error in Srapping check the url")
else:
    print("Successfully scrape the data")
    for x in soup.find_all('div',attrs={'class':'job-page'}):
        data.append({
            'pname':x.find(class_="profile-name").text.encode('utf-8'),
            'cname':x.find(class_="company_name").text.encode('utf-8'),
            'salary':x.find(class_="salary").text.encode('utf-8'),
            'lpa':x.find(class_="jobText").text.encode('utf-8'),
            'loc':x.find(class_="location").text.encode('utf-8')})

print("Loading data in csv")
with open('dataminer.csv', 'w') as f:
    fields = ['salary', 'loc', 'cname', 'pname', 'lpa']
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()
    writer.writerows(data)

【讨论】:

  • 您好,非常感谢您提供的代码,它真的很棒!我有一个问题,为什么 csv 文件中有一些不需要的内容?
  • 您可以使用replace() 替换那些不需要的内容,对于制表符和新行使用strip()
【解决方案2】:

除了您在其他答案中获得的内容外,您还可以同时抓取和写入内容。我使用.select() 而不是.find_all() 来达到同样的效果。

import csv
import requests
from bs4 import BeautifulSoup

URL = "https://www.myamcat.com/jobs"

page = requests.get(URL)
soup = BeautifulSoup(page.text, 'lxml')
with open('myamcat_doc.csv','w',newline="",encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(['pname','cname','salary','loc'])

    for item in soup.select(".job-listing .content"):
        pname = item.select_one(".profile-name h3").get_text(strip=True)
        cname = item.select_one(".company_name").get_text(strip=True)
        salary = item.select_one(".salary .jobText").get_text(strip=True)
        loc = item.select_one(".location .jobText").get_text(strip=True)
        writer.writerow([pname,cname,salary,loc])

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2021-04-19
    • 1970-01-01
    • 2018-12-25
    • 2016-04-22
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多