python中网页数据输出到csv操作方法

该博客展示了如何使用Python进行网页数据抓取,利用BeautifulSoup解析HTML,提取职位信息(包括职位名称、薪资和要求),并将数据存储到CSV和JSON文件中。代码实现了遍历HTML列表,找到特定类名的元素,获取其文本内容,并进行异常处理,确保数据的完整性和一致性。最后,将CSV和JSON文件进行追加写入。
摘要由CSDN通过智能技术生成

完整代码:

import json
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd
with open('web.html','r',encoding='gbk') as f:
    html=BeautifulSoup(f,'html.parser')
    html.list=html.find_all('div',attrs={'class':'e'})
    # print(html)
    # print(len(html.list))
    # print(html.list)
    job=[]
    for i,item in enumerate(html.list):
        try:
            print(item.find_all('span',attrs={'class':'jname at'})[0].text)
            print(item.find_all('span', attrs={'class': 'sal'})[0].text)
            print(item.find_all('span', attrs={'class': 'd at'})[0].text)
            # print(i)
            # print(item.find('span',attrs={'class':'jname'}).text)
            job.append({
                'jobname':item.find_all('span',attrs={'class':'jname at'})[0].text,
                'jobincome':item.find_all('span', attrs={'class': 'sal'})[0].text,
                'jobrequire':item.find_all('span', attrs={'class': 'd at'})[0].text,
            })
            #写入csv
            df=pd.DataFrame()
            df['jobname']=item.find_all('span',attrs={'class':'jname at'})[0].text,
            df['jobincome']=item.find_all('span', attrs={'class': 'sal'})[0].text,
            df['jobrequire']=item.find_all('span', attrs={'class': 'd at'})[0].text,
        except:
            continue
        # header = ['jobname', 'jobincome', 'jobrequire']
        df.to_csv('webT.csv',mode='a',header=None,index=None,encoding='utf-8-sig')#写入csv,mode=a+表示追加

    with open('web.json','w',encoding='utf-8') as f:
        json.dump(job,f,indent=1,ensure_ascii=False)
#写入csv
with open('web.json','r',encoding='utf-8') as f:
    data=json.load(f)

    with open('web.csv',mode='a',encoding='utf-8-sig',newline='') as f:
        writer=csv.writer(f)
        # header = ['jobname', 'jobincome', 'jobrequire']
        # writer.writerow(header)
        for item in data:
            writer.writerow([item['jobname'], item['jobincome'], item['jobrequire']])

        # for item in range(len(data)):
        #         writer.writerows(item)

        # writer.writerows(data)
        f.close()
    f.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

品尚公益团队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值