一个批量爬取图片的代码,拿走不谢

import io
import sys

import requests
from bs4 import BeautifulSoup
import os
if not os.path.exists("root"):
    os.mkdir("root")

max_page=1208
start_page=2
web="http://www.netbian.com"
test_url="/index.htm"
url="/index_{}.htm"
headers={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
}
pre_page=""
try:
    resp=requests.get(web+test_url,headers=headers)
    pre_page=resp.text
    resp.close()
    if not resp.ok:
        print("无法连接网站")
        quit()
except:
    print("无法连接网站异常")
    quit()

print("连接成功,正在爬取...")

for i in range(start_page,max_page+1):
    pageurl=web+url.format(i)
    try:
        resp=requests.get(pageurl,headers=headers)
        html_page=resp.text
        resp.close()
    except:
        print("无法爬取页面",i,"正在跳过")
        continue

    html_page=BeautifulSoup(html_page,"html.parser")
    div=html_page.find("div",class_="list")
    a=div.find_all("a")
    addr=[i.get("href") for i in a]
    de=[]
    for j in range(len(addr)):
        if str(addr[j]).find("http")<0:
            de.append(addr[j])
            
    print("在第{}个界面搜索到".format(i),de)
    if not os.path.exists("root/{}".format(i)):
        os.mkdir("root/{}".format(i))
    for ph in de:
        try:
            turl=web+ph
            
            tresp=requests.get(turl,headers=headers)
            tpage=BeautifulSoup(tresp.text,"html.parser")
            img_path=tpage.find("div",class_="pic").find("img").get("src")
            print("\r爬取",img_path,end="")
            tresp.close()
            tresp=requests.get(img_path,headers=headers)
            name=img_path.split("/")[-1]
            f=open("root/"+str(i)+"/"+str(name),"wb")
            f.write(tresp.content)
            tresp.close()
            f.close()
        except:
            print("\n")
            print("爬取{}失败...".format(ph))
            continue




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值