python爬取某省财政政策内容并保存为csv文件,最后用excel打开

文章直通车

  • 目标网址
  • 获取要求
  • 保存形式
  • 获取分析
  • 代码及主要注释
  • csv文件用excel打开问题

目标网址:http://czt.zj.gov.cn/col/col1164176/index.html

获取要求:获取每一条政策上的标题、政策文号、发布日期、发布机构以及发布的内容

在这里插入图片描述
保存形式:保存为csv文件,用excel打开形如:

在这里插入图片描述
分析:首先,我们需要获取每个政策的url,也就是li标签里面a标签的href属性值

在这里插入图片描述
然后根据获取的url去获取所需要的内容:
在这里插入图片描述
最后保存为csv文件

代码及主要注释

import requests
import re
from lxml import etree
import csv

# 通篇没有使用面向对象,因为个人觉得这样学习
column_name = ['title', 'ref_no', 'published_day',  'department', 'url', 'content']
with open('财政政策.csv', 'w', newline='') as f:
    csv_f = csv.writer(f)
    csv_f.writerow(column_name)

url = 'http://czt.zj.gov.cn/col/col1164176/index.html'

# 爬取第1页的数据,如若想要爬取多页的数据,可以用for循环并更改pageNum参数
params = {
    'uid': '5488355',
    'pageNum': 1
}

# 使用正则表达式匹配政策url的后半部分以构建url
response = requests.get(url, params=params).text
pat = '<a href="(.*?)"'
result = re.findall(pat, response, re.S)

# 从匹配的第7条数据开始,共15个,此后的是下一页的几条数据
for link in result[7:22]:
    content_url = f'http://czt.zj.gov.cn{link}'
    # print(content_url) 政策内容的url
    resp = requests.get(content_url).content.decode('utf-8')
    html = etree.HTML(resp)
    title = html.xpath('//div[@class="art_title"]/h2/text()')
    # print(title) 政策的标题
    ref_no = html.xpath('//div[@id="zoom"]//p[@style="text-align: center;"][1]/text()')
    # 因为HTML格式有所变换,所以有一个匹配到空格,便做了以下判断
    if ref_no[0].isspace():
        ref = html.xpath('//div[@id="zoom"]/p[2]/span/text()')
        ref_no = ''.join(ref).split()
    # 其中一个匹配到其他内容,所以做了以下判断
    keyword = '号'
    if keyword not in ref_no[0]:
        ref_no = html.xpath('//div[@id="zoom"]/p[2]/text()')
    # print(ref_no) 政策文号
    published_day = html.xpath('//div[@class="fz_xx"]/span/text()')[0][5:]
    # print(published_day) 政策发布日期
    department = html.xpath('//div[@class="fz_xx"]/span/text()')[3]
    # print(department) 政策发布机构
    content_list = html.xpath('//div[@id="zoom"]/p/text()')
    mark = '(换行)'
    content = mark.join(content_list).replace(' ', '')
    # print(content) 政策发布内容
    row_con = [f"{title[0]}", f"{ref_no[0]}", f"{published_day}", f"{department}", f"{content_url}", f"{content}"]
    with open('财政政策.csv', 'a', encoding='utf-8-sig', newline='') as f:
        csv_f = csv.writer(f)
        csv_f.writerow(row_con)
print('success')

csv文件用excel打开问题

最后在用excel打开的时候你可能会发现乱码,像这样:

在这里插入图片描述

就先以记事本形式打开
在这里插入图片描述

再点击文件另存为(也可以改掉编码为ANSI)

在这里插入图片描述
在这里插入图片描述

最终用excel打开就没有乱码了

也许你还可能发现发布日期为######,是因为列宽不够,增加列宽就可以啦

在这里插入图片描述

  • 6
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将爬取的网页内容保存CSV文件中,可以使用Python中的csv模块。具体步骤如下: 1. 导入相关模块: ```python import requests import csv from bs4 import BeautifulSoup ``` 2. 发送HTTP请求,获取网页内容: ```python url = 'http://www.example.com' response = requests.get(url) html_content = response.content ``` 3. 解析HTML内容,获取需要的信息: ```python soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string text = soup.get_text() ``` 4. 将获取的信息写入CSV文件: ```python with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Title', 'Text']) writer.writerow([title, text]) ``` 注意事项: - `csv.writer()`中`newline=''`参数的作用是防止写入CSV文件时出现空行; - CSV文件的编码一般为`utf-8`,中文字符需要特别注意编码问题。 完整代码示例: ```python import requests import csv from bs4 import BeautifulSoup url = 'http://www.example.com' response = requests.get(url) html_content = response.content soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string text = soup.get_text() with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Title', 'Text']) writer.writerow([title, text]) ``` 执行完毕后,当前目录下会生成一个名为`example.csv`的文件文件内容爬取的网页标题和文本。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值