python爬虫获取天气

3 篇文章 0 订阅
1 篇文章 0 订阅

爬取天气

首先这串代码是我爬取天气网的相关信息,用到的有lxml和requests,用requests获取网页内容通过etree和xpath提取其中的相关信息,keyword是要输入的城市名字,可以随意修改目前已存在的城市,如果大家有什么问题欢迎留言。

import requests
from lxml import etree

def get_weather(keyword):
    url = 'https://www.tianqi.com/tianqi/search?keyword=' + keyword
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    response = requests.get(url,headers=headers)
    response.raise_for_status()
    response.encoding=response.apparent_encoding
    tree = etree.HTML(response.text)
    # 检测城市天气是否存在
    try:
        city_name = tree.xpath('//dd[@class="name"]/h2/text()')[0]
    except:
        content = '没有该城市天气信息,请确认查询格式'
        return content
    week = tree.xpath('//dd[@class="week"]/text()')[0]
    now = tree.xpath('//p[@class="now"]')[0].xpath('string(.)')
    temp = tree.xpath('//dd[@class="weather"]/span')[0].xpath('string(.)')
    shidu = tree.xpath('//dd[@class="shidu"]/b/text()')
    kongqi = tree.xpath('//dd[@class="kongqi"]/h5/text()')[0]
    pm = tree.xpath('//dd[@class="kongqi"]/h6/text()')[0]
    content = "【{0}】{1}天气\n当前温度:{2}\n今日天气:{3}\n{4}\n{5}\n{6}".format(city_name, week.split('\u3000')[0], now, temp, '\n'.join(shidu),kongqi,pm)
    print(content)

if __name__ == "__main__":
    keyword = '北京'
    content = get_weather(keyword)    
  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值