import requests from lxml import etree

设置url,爬取你所在城市的7日天气

url = 'http://www.weather.com.cn/weather/101010100.shtml'

设置headers,为你本机的User-Agent。

headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

通过requests.get发起请求response

response = requests.get(url, headers=headers)

把响应的内容response解码为utf-8格式

html = response.content.decode('utf-8')

用etree.HTML把解码后的response转换成DOM树格式

dom_tree = etree.HTML(html)

通过xpath匹配所在城市的最高温度的结果,用完整路径(方法1)

max_temperature = dom_tree.xpath('/html/body/div[7]/div[2]/div[1]/div[2]/ul/li[1]/p[2]/i/text()')[0]

通过xpath匹配所在城市的最低温度的结果,用相对路径(方法2)

min_temperature = dom_tree.xpath('//div[@class="tem"]/span/text()')[0]

打印输出最高温度,最低温度

print('最高温度:', max_temperature) print('最低温度:', min_temperature

导入requests库导入etree库设置url爬取你所在城市的7日天气设置headers为你本机的User-Agent。通过requestsget发起请求response把响应的内容response解码为utf-8格式用etreeHTML把解码后的response转换成DOM树格式通过xpath匹配所在城市的最高温度的结果用完整路径方法1通过xpath匹配所在城市的最低温度的结果用相对路径方法2

原文地址: http://www.cveoy.top/t/topic/eY1j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录