python爬虫之豆瓣首页图片爬取

网址:https://movie.douban.com/

python 复制代码
import requests
from lxml import etree
import re
url = 'https://movie.douban.com'
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36'
}
session = requests.session()
response = session.get(url,headers = headers)
# response.encoding='utf-8'
# response.encoding = response.apparent_encoding
index_url = 'https://movie.douban.com'
res = session.get(index_url,headers=headers)
# print(res.text)
# 输出:页面源代码
tree = etree.HTML(res.text)
# print(tree)
# 输出:<Element html at 0x186fa6a3100>
img_all = tree.xpath('//img')
# print(img_all)
for i in img_all:
    img = etree.tostring(i, encoding='UTF-8').decode('UTF-8')
    # 得到所有的img标签
    # print(img)
    # <img src="https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2900931370.jpg" alt="&#x5C0F;&#x884C;&#x661F;&#x730E;&#x4EBA;" rel="nofollow" class=""/>
    img_url = tree.xpath('//img/@src')
    # img_name = tree.xpath('//img/@alt')
    # print(img_url,img_name)
    # 输出:许多个列表
    for i in img_url:
        # print(i)
        last_str = i.split('/')[-1]
        # print(last_str)
        # 输出:多个p2900931370.jpg  p2901057189.jpg
        every_name = last_str.split('.')[0]
        # print(every_name)
        # 输出:多个p2900931370  p2901057189
        res_url = session.get(i,headers=headers)
        with open(f'./img/{every_name}.jpg','wb') as f:
            f.write(res_url.content)

运行结果:

相关推荐
zhangzeyuaaa几秒前
深入理解 Ruby 运算符:本质、分类、坑点与重载实战
开发语言·前端·ruby
一木 之林4 分钟前
DeepSeek Agent 开发(一)
开发语言·前端·javascript
朔北之忘 Clancy5 分钟前
青少年软编等考七级题解目录
开发语言·c++·青少年编程·gesp·csp·信奥赛·noi
ss27317 分钟前
AI全栈实战 | 3.2-01 Python 基础:四大数据容器怎么选,推导式为什么是 Pythonic 的灵魂
开发语言·人工智能·python
Mr_Macallon24 分钟前
C++回顾(基础)(01)
c语言·开发语言·c++·学习
计算机毕业编程指导师27 分钟前
【大数据毕设选题推荐】基于Spark的WTA职业网球赛事演变与竞技格局分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习 深度学习
大数据·python·计算机·spark·毕业设计·课程设计·wta网球
未来之窗软件服务35 分钟前
Go 利器 GoReSym:剥离符号恢复 Go 二进制元数据—东方仙盟
开发语言·golang·仙盟创梦ide·东方仙盟
言乐61 小时前
Python区分广度优先深度优先宽度优先的区别
python·算法·深度优先·广度优先·宽度优先
打工仔折腾 AI1 小时前
LLaMA 1 到 LLaMA 3 架构演进拆解:从 RoPE、GQA 到词表扩张
人工智能·后端·python·深度学习·langchain·llama
朝朝辞暮i1 小时前
C++ 第 32 课:main()、rclcpp::init()、spin()、shutdown()
开发语言·c++·算法