inpm
! dlrow olleH

python爬旅游景点并导出Excel

2019-08-23 python
Word count: 570 | Reading time: 2min

起因

  • 高中同学找帮忙,需要做一个丽江旅游景点的excel
  • 有之前爬过初高中考题经历
  • 把这个任务当作检验自己python爬虫的掌握情况
  • 从零开始

要求及难点

  • 丽江全部旅游景点信息,包括景点名字、位置、特点、介绍、经纬度
  • 经纬度在网站中没有体现,这里需要根据正则匹配到位置然后掉百度地图API查询
  • python中对json的解析
  • 写入Excel

代码讲解

用到哪些包

1
2
3
4
5
import urllib.request
import requests
import xlsxwriter
import re
from bs4 import BeautifulSoup

  • urllib读取链接,requests解析get请求,xlsxwriter写入Excel,re做正则,BeautifulSoup页面解析

写Excel函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 建表
workbook = xlsxwriter.Workbook('丽江全部景区.xlsx')
worksheet = workbook.add_worksheet('丽江')
# 将数据写入工作表中
def writeExcel(row=0, name='', tag='', intro='', position=''):
print(row)
if row == 0:
worksheet.write(row, 0, '景区名')
worksheet.write(row, 1, '标签')
worksheet.write(row, 2, '介绍')
worksheet.write(row, 3, '经纬度')
else:
worksheet.write(row, 0, name)
worksheet.write(row, 1, tag)
worksheet.write(row, 2, intro)
worksheet.write(row, 3, position)

  • 记得递增row

请求百度地图API并解析json

1
2
3
4
5
6
7
8
9
10
if place == 'none':
position = 'none'
else:
#获取json格式的url
positionUrl = 'http://api.map.baidu.com/geocoder?address=' + place + '&output=json&key=f247cdb592eb43ebac6ccd27f796e2d2'
r = requests.get(positionUrl)
if type(r.json()['result']) == list:
position = 'none'
else:
position = str(r.json()['result'])

  • 中间涉及python中dict(字典)转str,list(数组)转str,还有一些缺省值的判断,解析json的时候对r执行.json()方法即可拿到dict再转成str存入表中

一个shell脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

rm ./tmpcache -rf
rm '丽江全部景区.xlsx'

cachedir='./tmpcache'

if [ ! -d ${cachedir} ]; then
mkdir -p ${cachedir}
fi

# 页码,进详情,抓内容
python3 1_lijiang.py > ${cachedir}/lj.txt | uniq > ${cachedir}/lj.txt

  • 这里每次做清空缓存的处理,然后再执行爬虫脚本

总结

  • 对页面/接口编码规范有多认识
  • 代码中因为有模拟点击下一页和进入详情的操作,套了3个for循环,这里应该再考虑下有没有其他办法
  • 做的过程中遇到了很多语法报错的小问题,应及时加强python的语法学习
  • 加深了对缺省值的判断,数据类型的转换理解
  • 全程大概用时⌚️3小时,最终成功交付给同学完成任务✅

Author: inpm.cy@gmail.com

Link: https://inpm.top/2019/08/23/python爬旅游景点并导出Excel/

Copyright: All articles in this blog are licensed under inpm unless stating additionally.

< PreviousPost
为2020搭建自己的技术壁垒
NextPost >
go开发总结
CATALOG
  1. 1. 起因
  2. 2. 要求及难点
  3. 3. 代码讲解
  4. 4. 总结