Python爬虫爬取src图片

Python爬虫爬取图片

需要用到的库:
os
time
request
lxml

代码源码如下:

import os
import time
import requests
from lxml import etree
#建议headers写全 也可以只写user-agent和cookie
headers = {
'User-Agent':'xxxxxx',
'Accept': 'xxxxxx',
'Accept-Encoding': 'xxxxxx',
'Accept-Language': 'xxxxxx',
'Connection': 'xxxxxx',
'Cookie': 'xxxxxx',
'Referer': 'xxxxxx'
}
#单页面爬取
#先请求获得想要爬取图片的当前网页源码
#可以使用print打印到控制台分析也可以在网页中使用F12查看分析
response = requests.get('http://xxxxxx.com/xxx?xxx',headers=headers)

# print(response.content.decode())
html = etree.HTML(response.content.decode())
#使用xpath获取图片源
#img标签下的
imgs = html.xpath("//img//@file")
for i in imgs:
	#睡眠3秒
    time.sleep(3)
    #可能需要进行链接拼接
    url2 = ("http://xxxxxx.com/"+i)
    print(url2)
    #保存图片名
    #以'/'做分隔符 截取倒数第一个作为图片名
    file_name = url2.split('/')[-1]
    print(file_name)
    #请求图片源
    #content中间存的是字节码 保存图片使用content
    img_data = requests.get(url2, headers=headers).content
    #创建文件夹
    if not os.path.exists('./xx'):
        os.mkdir('./xx')
    img_path = './xx/' + file_name
    with open(img_path, 'wb') as f:
        f.write(img_data)


xpath 选择
在这里插入图片描述

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫中,如果要爬取图片src属性,你可以使用requests库和BeautifulSoup库进行处理。首先,你需要发送一个请求来获取网页的源码。然后,使用BeautifulSoup库来解析网页内容,并通过find_all函数来查找img标签。在img标签中,你可以使用get方法获取src属性的值,并将它代给下一个函数进行处理。以下是一个简单的代码示例: ```python import requests from bs4 import BeautifulSoup def get_image_src(url): response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") img_tags = soup.find_all("img") for img_tag in img_tags: src = img_tag.get("src") print(src) # 在这里可以对src进行进一步处理,如下载图片 # 调用函数并传入要爬取的网页url get_image_src("http://example.com") ``` 这个示例中,首先使用requests库发送请求获取网页的源码。然后,使用BeautifulSoup库对源码进行解析,并通过find_all函数查找所有的img标签。在循环中,使用get方法获取img标签的src属性值,并进行进一步处理,比如打印输出或下载图片。你可以根据自己的需求对这个代码进行修改和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python爬虫爬取src图片](https://blog.csdn.net/weixin_54250368/article/details/122192440)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python爬虫爬取图片](https://blog.csdn.net/weixin_52136304/article/details/116357805)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值