PYTHON 2.7爬虫获取豆瓣丑女的照片,备注信息稍后更新

#encoding=utf-8
import urllib2
import urllib
from bs4 import BeautifulSoup
import os
import time
import requests

def crawl():
    global count
    global counl
    count = 0
    # url = 'https://www.dbmeinv.com/index.htm'所有
    # 选择channel
    for i in range(4,7):
        #选择对应的页码数
        for j in range(1, 5):
            url = 'https://www.dbmeinv.com/index.htm?cid=%d&pager_offset=%d' %(i, j)

            #伪装头部
            headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}

            #发送Request请求
            req = urllib2.Request(url, headers=headers)

            #获取page页面
            page = urllib2.urlopen(req)

            #输出获取得到的页面
            contents = page.read()

            #使用soup解析html页面
            soup = BeautifulSoup(contents, 'lxml')

            # 指定规则在contents中找到我们想要的网络资源
            chou_girl = soup.find_all("img")

            # 将图片写入到我们的程序所在的当前文件夹中去
            count = 0
            # print type(chou_girl)

            # 遍历每一个元素

            for girl in chou_girl:
                counl = 0
                # 获取其中每个img标签中的src属性,即它的文件地址
                link = girl.get("src")
                # 获取标题,以后可以作为图片文件的名字来使用
                title = girl.get("title")
                title = title.replace("?", "?")
                title = title.replace('"', '“')
                title = title.replace('/', '')
                title = title.replace('%', '')

                # 计数,方便我们统计共有多少个文件被下载。。注意一点就是如果文件重名了,,后面的文件将会覆盖之前下载的文件。
                count += 1

                # print type(title)
                print '第{}channel中第{}页的第{}张图片\t'.format(i, j, count) + title,
                print link
                response = urllib2.urlopen(link)
                img = response.read()

                if not os.path.exists('img/{}.jpg'.format(title)):
                    counl = 0
                    with open('img/%d-%d-%d-%s_%d.jpg' % (i, j, count, title, counl), 'wb') as f:
                        f.write(img)
                        f.close()
                elif os.path.exists('img/{}.jpg'.format(title)):
                    counl += 1
                    with open('img/%d-%d-%d-%s_%d.jpg' % (i, j, count, title, counl), 'wb') as f:
                        f.write(img)
                        f.close()

            time.sleep(2)
        time.sleep(3)
    print count*2*4

#确保本文件如果被当作库文件引用时,只会输出结果,里面的内容不会重复输出。
if __name__ == "__main__":
    crawl()

猜你喜欢

转载自blog.csdn.net/qq_32670879/article/details/81363416