一、获取网址
1.新建一个python文件![](https://i-blog.csdnimg.cn/blog_migrate/6b516a0e0d7f376cfd331ac363b32b31.png)
2.获取请求头
进入天气网:天气网 (weather.com.cn)
打开开发者模式
解析为python代码
网址:Convert curl commands to code (curlconverter.com)
将解析的内容复制到python
3.导入etree库
from lxml import etree
如果没有lxml库先下载
4.下载lxml(如已有可跳过)
pip install lxml
二、设置编码格式
1.添加天气网地址
weather_url='http://www.weather.com.cn/'
2.打印状态码
print(response.status_code)
这里如果报错可能是编码格式的问题,将编码格式设置为utf-8
3.修改编码模式
修改成功后重新打印状态码
4.打印编码格式与源编码格式
#打印编码模式
print(response.encoding)
#源编码模式
print(response.apparent_encoding)
5.设置编码格式与源编码格式相等
#设置编码模式为源编码模式
response.encoding=response.apparent_encoding
三、网页图片下载
1.查看下载页
打印下载页内容
#查看下载页,打印文本内容
print(response.text)
2.解析网页
使用etree解析网页
#使用etree解析网页
selector=etree.HTML(response.text)
解析图片路径
获取图片路径
复制图片的xpath路径
将路径补充完整
打印地址
3.将图片写入本地文件
#将图片写入本地文件which
response_image=requests.get(image_ditu)
with open('weather.jpg','wb') as image:
image.write(response_image.content)
写入成功