Python爬虫爬取录用公务员职位表并保存为Excel表

本文介绍了使用Python爬虫从陕西省政府网站抓取2021年公务员职位信息的过程。通过分析网页源代码,发现原始HTML中并未直接包含数据,而是在网络请求中加载。利用requests和BeautifulSoup库解析页面,找到隐藏的数据表格,并使用xlwt模块将数据写入Excel文件。完整代码展示了如何处理网页编码问题,以及如何遍历表格内容并写入Excel。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备工作:

  Python版本 python3.7

  Python库:requests, bs4, xlwt

目标网址:http://www.shaanxi.gov.cn/xw/ztzl/zxzt/zkzl/2021/2021gwy/202102/t20210222_2153937.html

网页分析:

这个网站的内容用我之前写的博客Python爬虫爬取小说中的方法是不能爬取成功的。复制了表格中的selector值,但是在调试的时候发现找不到这个selector,找不到表格的内容。

后来通过F12启动调试模式,刷新网页,然后看Network项,发现有一个html页面下载了好长时间,然后终于在里面找到了想要的数据:

找到了数据的位置,然后可以通过BeautifulSoup模块的find方法来定位元素:

import requests
import xlwt
from bs4 import BeautifulSoup

url = 'http://www.shaanxi.gov.cn/xw/ztzl/zxzt/zkzl/2021/2021gwy/202102/t20210222_2153937.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.find('table')

找到了整个表之后,然后就可以顺藤摸瓜,找到表内的元素,最后再按照行列将数据写入到Excel中就可以了:

xlwt是一个比较简单方便写入Excel表的模块:xlwt API介绍。主要用到的就是xlwt.Worksheet.Worksheet类的write方法,向指定坐标的单元格写入文字。

enc = response.encoding
workbook = xlwt.Workbook(encoding='utf-8')
sheet = workbook.add_sheet('sheet1')

col,row = 0,0
table = data.contents[1]
for row_items in table.contents:
    for item in row_items.contents:
        item_str = item.getText().encode(enc).decode('utf-8')
        sheet.write(row, col, item_str)
        col += 1
    row += 1
    col = 0

注意:网页的编码格式可以通过requests.models.Response类中的成员encoding获取。比如,这个网页的编码格式就是ISO-8859-1的格式,不是我们常用的UTF-8格式,所以在获取文字的时候需要进行一个转码的操作。

最后,保存Excel文件即可:

with open(path, 'wb') as f:
    workbook.save(f)

完整代码

import requests
import xlwt
from bs4 import BeautifulSoup

url = 'http://www.shaanxi.gov.cn/xw/ztzl/zxzt/zkzl/2021/2021gwy/202102/t20210222_2153937.html'

path = r'F:\Code\Python\crawler\陕西省2021年统一考试录用公务员职位表.xls'

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36",
}

response = requests.get(url)
print("get response success!")
soup = BeautifulSoup(response.text, 'html.parser')
print("soup parser success!")
data = soup.find('table')
if len(data) > 0:
    print("get data sucess!")
else:
    print("get data failed!")
    exit(1)

enc = response.encoding
print("encoding = ", enc)

workbook = xlwt.Workbook(encoding='utf-8')
sheet = workbook.add_sheet('sheet1')

col,row = 0,0
table = data.contents[1]
for row_items in table.contents:
    for item in row_items.contents:
        item_str = item.getText().encode(enc).decode('utf-8')
        sheet.write(row, col, item_str)
        col += 1
    row += 1
    col = 0

print("gather data sucess!")

with open(path, 'wb') as f:
    workbook.save(f)

print("save data sucess!")

生成的Excel内容:

最后

我还是个爬虫菜鸟,只能爬一些不设防的简单网页。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值