爬虫入门(三)

前面我们找到网站的url和伪装浏览器之后就可以写代码了

res = requests.get(add,headers=headers)
soup = BeautifulSoup(res.text,'lxml')
img_list = soup.find_all('img',attrs={'class':'lazy image_dtb img-responsive'})#class 中是图片下载路径

def download_img(url):
    split_list = url.split('/')#图片名分割
    filename = split_list.pop()
    path = os.path.join("images")#图片的路径
    # 判断是否有这个文件夹没有的话创建文件夹
    if not os.path.exists(path):
        os.mkdir(path)
    else:
        mypath=os.path.join("images",filename)
        request.urlretrieve(url,filename=mypath)

for img in img_list:
    img_really = img['data-original']
    download_img(img_really)

  项目写完了有个缺点就是因为url是在网址上拿到的所以要拿下一页的url就要手动更改,也可以写个循环遍历url

posted @ 2018-11-27 11:47  浮生若梦不悔  阅读(126)  评论(0编辑  收藏  举报