利用beautiful soup爬取历史天气数据

利用beautiful soup爬取历史天气数据
本文将会涉及requests.get()返回结果为404时,采用模拟浏览器访问的模式。以及当遇到几个相同的标签时的处理办法。由于本人还是个小白,故可能有不好的地方
参考了:https://www.jianshu.com/p/10cb1502e525以及
https://blog.csdn.net/zenobia119/article/details/79811770文章
爬取的网站为http://lishi.tianqi.com/
代码如下

//
"""
目标:
爬取2019年香洲的天气数据,包括最高气温,最低气温,天气,风向
并将数据储存到xiangzhou.txt中
在bs4中若遇上相同的标签,则使用find_next()
该程序还加上当遇到反爬虫时利用模拟浏览器访问的方式进行爬取
"""
import requests
from bs4 import BeautifulSoup
import time
"""定义一个抓取页面内容的函数"""
def get_html(url):
    try:
        #使用该句模拟浏览器访问
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                                 'Chrome/51.0.2704.63 Safari/537.36'}
        r = requests.get(url, headers=headers, timeout=30)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        return "error"
def get_content(url,tianshu):
    comments = []
    html = get_html(url)
    #做汤
    """lxml HTML解析器"""
    soup = BeautifulSoup(html, "lxml")
    # 按照之前的分析,我们找到所有具有‘ j_thread_list clearfix’属性的li标签。返回一个列表类型。
    uls = soup.find('ul', attrs={'class': 'thrui'})
    for i in range(tianshu):
        uls = uls.find_next('li')
        # 初始化一个字典来存储文章信息
        comment = {}
        # comment = {'title': None ,'link': None, 'name': None,'time': None,'replyNum': None}
        # 开始筛选信息,并保存到字典中
        try:
            comment['riqi'] = uls.find('div', attrs={'class': 'th200'}).text.strip()
            comment['maxt'] = uls.find('div', attrs={'class': 'th140'}).text.strip()
            mint = uls.find('div', attrs={'class': 'th140'}).find_next('div')
            comment['mint'] = mint.text.strip()
            tianqi = mint.find_next('div')
            comment['tianqi'] = tianqi.text.strip()
            fengxiang = tianqi.find_next('div')
            comment['fengxiang'] = fengxiang.text.strip()
            comments.append(comment)
        except:
            print('出了点小问题')
    return comments
def out2file(dict):
    """
    定义一个函数将爬取到的文件写入本地,保存到当前目录的abc.txt文件中
    """
    with open('xiangzhou.txt','a+') as f:
        for comment in dict:
            f.write(comment['riqi']+'\t'+comment['maxt']+'\t'+comment['mint']+'\t'+comment['tianqi']+'\t'+comment['fengxiang'])
            f.write('\n')
        print("当前页面爬取完成")
def main(base_url,yue):
    url_list = []
    deep = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
    for i in range(12):
        url_list.append(base_url + deep[i] + '.html')
    print("所有网页已经下载到本地")
    #循环写入所有的数据
    for i in range(len(url_list)):
        content = get_content(url_list[i],yue[i])
        out2file(content)
    print ("所有的信息都已经保存完毕")
if __name__ == "__main__":
    base_url = "http://lishi.tianqi.com/xiangzhouqu/2019"
    # 设置需要爬取的页码数量
    #deep = 3
    yue = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    main(base_url,yue)


结果如下图所示
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值