python 利用xpath 爬取一周天气

需求:

爬取 中国天气网指定城市一周的天气,以天津为例

实现:

1,先找到一周的数据位置。

 divs = html.xpath("//div[@class='hanml']")

2,再遍历每天。

trs = div.xpath("./div/div[2]/table//tr[position()=1]")  

3,获取每天的最高气温 最低气温。

city_data['max_tem'] = int(tr.xpath("./td[@width='92']/text()")[0])  #  得到城市最高气温

 city_data['min_tem'] = int(tr.xpath("./td[@width='86']/text()")[0])  #  得到城市最低气温

代码:

import requests
from lxml import etree

BASE_URL = 'http://www.weather.com.cn/textFC/tianjin.shtml' 

#  爬取一个网页数据
def get_data():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    } 
    try:
        response = requests.get(BASE_URL, headers= headers)
        response.raise_for_status()
        response.encoding = 'utf-8' 
        #  在打开文件的时候需要指出编码方式,否则会报错
        with open('data.txt', 'w', encoding='utf-8') as fp:
            fp.write(response.text)
    except:
        print("爬取数据失败")

#  解析网页数据
def get_usefuldata():
    with open('data.txt', 'r', encoding='utf-8') as fp:
        text = fp.read()
    html = etree.HTML(text)
    
    #得到所有天气
    divs = html.xpath("//div[@class='hanml']") 
    for div in divs:
        #  获取第1个tr标签
        trs = div.xpath("./div/div[2]/table//tr[position()=1]")  
        for tr in trs:
            city_data = {}
            city_data['max_tem'] = int(tr.xpath("./td[@width='92']/text()")[0])  #  得到城市最高气温
            city_data['min_tem'] = int(tr.xpath("./td[@width='86']/text()")[0])  #  得到城市最低气温
            print(city_data)


def main():
    get_data()
    get_usefuldata()


if __name__ == '__main__':
        main()

效果:

相关推荐

  1. Python天气信息,并进行语音播报

    2024-04-06 14:36:02       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-06 14:36:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-06 14:36:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-06 14:36:02       87 阅读
  4. Python语言-面向对象

    2024-04-06 14:36:02       96 阅读

热门阅读

  1. xv6源码分析 001

    2024-04-06 14:36:02       41 阅读
  2. Python编程-使用logging管理程序日志

    2024-04-06 14:36:02       34 阅读
  3. 如何DEBUG ABAP程序中的循环语句

    2024-04-06 14:36:02       38 阅读
  4. 【数据结构】串

    2024-04-06 14:36:02       39 阅读
  5. 达梦体系结构:进程架构

    2024-04-06 14:36:02       32 阅读