使用python抓取今日头条图集数据

暖场篇

 前一段时间一直在忙着开发公司的项目,博客更新就被搁置下来了,最近稍得空闲,就重温了一下python,用python抓取今日头条的图集.

源码传送门

剧情篇

我们一起来开始python爬虫之旅吧.

准备工作

  • 开发工具
    PyCharm(python开发IDE)

  • 需要的python包
    pymongo (用来将抓取到的数据存储到数据库中)

sudo pip install pymongo

  BeautifulSoup (用来解析html文本)

sudo pip install BeautifulSoup4

开始抓包

分析目标站点

 主要是分析目标网页的网络请求方式和数据处理方式,找到自己所需要抓取的数据的网络请求并记录下来

创建python工程

请求列表页面的数据

 拼装data数据,并通过requests模块进行网络请求,获取到搜索列表页的数据

def get_page_index(offset, keyword):
    data = {'offset': offset,
            'format': 'json',
            'keyword': keyword,
            'autoload': 'true',
            'count': 20,
            'cur_tab': 3
            }
    url = 'http://www.toutiao.com/search_content/?' + urllib.urlencode(data)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        print  ('请求索引失败 ')
        return None
解析列表页面的数据
def parse_page_index(html):
    data = json.loads(html)
    if data and 'data' in data.keys():
        for item in data.get('data'):
            yield item.get('article_url')
获取详情页数据
def get_page_detail(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        print  ('请求详情页失败')
        return None
解析详情页面的数据

 这里需要注意的点是使用BeautifulSoup包解析网页时,需要先下载好lxml的解析器
 使用json.loads()方法可以将string类型的数据转化成键值对,需要注意的点是jsonString中不能包含空格,否则会解析失败需要先使用strJson = "".join([jsonString.strip().rsplit("}", 1)[0], "}"])对字符串进行处理

def parse_page_detail(html, url):
    soup = BeautifulSoup(html, "lxml")
    # print  '调用成功'
    title = soup.select('title')[0].get_text()
    images_pattern = re.compile('gallery: (.*?)siblingList:', re.S)
    result = re.search(images_pattern, html)
    if result:
        jsonString = result.group(1)
        # 这句话是解析的关键问题
        strJson = "".join([jsonString.strip().rsplit("}", 1)[0], "}"])
        data = json.loads(strJson)
        if data and "sub_images" in data.keys():
            sub_images = data.get("sub_images")
            images = [item.get("url") for item in sub_images]
            for image in images: download_image(image)
            return {
                'title': title,
                'url': url,
                'images': images
            }
        return None
    return None
存储数据库

连接数据库

client = pymongo.MongoClient(MONGO_URL,8000)
db = client[MONGO_DB]

将抓取到的数据存储导数据库中

def save_to_mongo(result):
    if db[MONGO_TABLE].insert(result):
        # print ('存储到MongoDB成功')
        return True
下载图片
def download_image(url):
    print '正在下载图片 %s' % url
    try:
        response = requests.get(url)
        if response.status_code == 200:
            save_image(response.content)
        return None
    except RequestException:
        print  ('下载图片出错 ')
        return None
存储图片到磁盘
def save_image(content):

    imagePath = os.path.join(os.getcwd(),KEYWORD)
    if not os.path.exists(imagePath):
        os.mkdir(KEYWORD)

    file_path = '{0}/{1}.{2}'.format(imagePath, md5(content).hexdigest(), 'jpg')
    if not os.path.exists(file_path):
        with open(file_path, 'wb') as f:
            f.write(content)
            f.close()
开启多线程
    groups = [x * 20 for x in range(GROUP_START + 1, GROUP_END + 1)]
    pool = Pool()
    pool.map(start_spider, groups)

总结

  通过以上这几个步骤就可以完成爬虫获取数据的功能,针对不同的网站由于数据格式和数据处理方式不同,我们需要用不同的方式去抓取数据和解析数据,但是原理和思路是不变的.

使用python进行抓包大概分为:
  • 分析要抓取的网页的请求方式,数据处理方式.
  • 使用python对获取到的数据进行过滤(正则表达式)
  • 将抓取到的数据存储到数据库
  • 使用多线程加快任务执行速度

结束语

我们可以断言,没有激情,任何伟大的事业都不能完成. --黑格尔

你可能感兴趣的:(使用python抓取今日头条图集数据)