使用简单爬虫获得一些信息数据
前言
在自己开发一些网站或者公众号时,为了让自己的功能更全面化,往往会去一些外部网站调用一些功能性的Api。这些外部网站的Api,往往收费或者限制次数,这就让人很苦恼,我就想自己学了爬虫,为啥自己不做一个类似Api一样的函数,获得数据信息。本文章举例爬取天气信息供使用。
源码已经上传我的gitee库可自行下载使用。
一、准备工作,寻找目标网站
上网搜索寻找可以简单爬取的网站,在你找到目标网站后,进入开发者工具-网络选项。刷新页面,找到文档选项,这就是网页的我们能爬取到的内容,点击查看里面是否有我们需要的数据,如果有,则这个文档类文件就是我们能爬取得到的网站资源。没有,就换。如下图,所示,这样的网站我们就可以使用简单的爬虫爬取。
二、确定需要的数据
确定了这个网站能爬取,点开网站看,查看里面你需要的数据,示例如下:
比如数据图一都是我们需要的数据,点开刚刚在网络文档找到的网站源码,查看里面源代码是否有这些数据。如下: 三、 代码实现
1.获得自己的网站cookie
还是在开发者网络-文档网页文件里面,点击标头,里面的请求标头里面有,示例如下:
2.代码实现
import sys
import requests
import re
import pandas as pd
if __name__ == '__main__':
headers = {
'user-agent': '',
'Cookie': ''
}
name_place = input('请输入所在地名:')
try:
data = pd.read_excel('cityinfo.xls', index_col='城市名称')
code = data.loc[name_place]['对应代码']
except:
print('输入错误!!')
sys.exit()
url = 'https://weather.cma.cn/web/weather/{}.html'.format(code)
res = requests.get(url=url, headers=headers)
# 避免爬取网页编码格式不和请求文本导致乱码
res.encoding = res.apparent_encoding
# print(res.text)
seven_dayList = re.findall('<div class="day-item">\n (.*?)\n </div>', res.text, re.S)
print(seven_dayList)
tem_high = re.findall('<div class="high">\n (.*?)\n </div>', res.text, re.S)
print(tem_high)
tem_low = re.findall('<div class="low">\n (.*?)\n </div>', res.text, re.S)
print(tem_low)
total_list = re.findall('<td style="background-color:#eee;">(.*?)</tr>', res.text, re.S)
# print(total_list)
# print(len(total_list))
final_totalList = total_list.copy()
temp = 0
for i in range(0, len(total_list)):
if '天气' in total_list[i]:
del final_totalList[i - temp]
temp = temp + 1
print(final_totalList)
list_info = []
for m in range(0, len(final_totalList)):
list_info.append(re.findall('<td>(.*?)</td>', final_totalList[m]))
print(list_info)
全部文件数据在我的gitee库可自行下载使用
3.效果实现