使用requests爬取猫眼电影TOP100榜单

  Requests是一个很方便的python网络编程库,用官方的话是“非转基因,可以安全食用”。里面封装了很多的方法,避免了urllib/urllib2的繁琐。

  这一节使用requests库对猫眼电影的TOP100榜进行抓取。

1 获得页面。

首先确定要爬取的url为http://maoyan.com/board/4,通过requests模块,打印出页面的信息

def get_a_page(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:#状态码,200表示请求成功
            return response.text #返回页面信息
        return None
    except RequestException :
        return  None

上面是代码及注释,为了防止再抓取时候出现异常,requests的异常有这些,其中RequestException是异常的父类,故我们直接导入

from requests.exceptions import RequestException

作为异常处理。这样就得到了该url地址的网页内容。

2 分析页面

  首先看一些页面的大致情况,其中【霸王别姬】就是我们要抓取的栏目,栏目下面又分了一些小内容,如下面黑色箭头所示。

先看一下页面大致情况,右键【审查元素】

可以看出<dd>标签包裹着每一个电影的信息,用正则表达式找到想要的元素。

reg = re.compile(‘<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name">‘
                     + ‘<a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>‘
                     + ‘.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>‘,re.S)

依次捕获的是 排名,地址,名称,主演,时间,整数评分,小数评分。这里我用字典的形式存储,返回一个生成器。

items = reg.findall(html)
    for item in items:
        yield{
            "index":item[0],
            "image":item[1],
            "title":item[2],
            "actor":item[3].strip()[3:],
            "time":item[4].strip()[5:],
            "score":item[5]+item[6]
            }

3 写入文件

抓取到电影列表,剩下就是将电影列表写入文件中,由于返回的是一个字典对象,可以使用pickle方法进行序列化,但为了方便以后的查阅,这里用文本方式保存

def write_to_file(contents):
    c = ""
    with codecs.open("result.txt",‘a‘,encoding="utf-8",errors="ignore") as f:
        for key,value in contents.items():
            c += key + ":" + value +"\t"
        f.write(c + "\n")

返回的是一个字典格式,可是借助json方法进行序列化

def write_to_file(contents):
    with codecs.open("result.txt",‘a‘,encoding="utf-8",errors="ignore") as f:
        f.write(json.dumps(contents,ensure_ascii=False) + ‘\n‘)

其中的dumps方法是将obj序列化为JSON格式的字符串,这里面要注意的是编码问题。最后就是抓取整个榜单了,可以加入多线程策略,最后的完整代码

# -*- coding: utf-8 -*-

import requests,re
import codecs
from requests.exceptions import RequestException
from multiprocessing import Pool

import json
def get_a_page(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException :
        return  None
def parse_a_page(html):
    #排名,地址,名称,主演,时间,评分1,评分2
    reg = re.compile(‘<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name">‘
                     + ‘<a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>‘
                     + ‘.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>‘,re.S)
    items = reg.findall(html)
    for item in items:
        yield{
            "index":item[0],
            "image":item[1],
            "title":item[2],
            "actor":item[3].strip()[3:],
            "time":item[4].strip()[5:],
            "score":item[5]+item[6]
            }

def write_to_file(contents):#这里面两个方法。一种是用json,一种是转为字符串
    c = ""
    with codecs.open("result.txt",‘a‘,encoding="utf-8",errors="ignore") as f:
        #for key,value in contents.items():
            #c += key + ":" + value +"\t"
        f.write(json.dumps(contents,ensure_ascii=False) + ‘\n‘)
        #print c
        #f.write(c + "\n")
def main(offset):
    url = "http://maoyan.com/board/4?offset=%s" %offset
    print url
    html = get_a_page(url)
    for item in parse_a_page(html):
        write_to_file(item)

if __name__ == "__main__":
    ‘‘‘
    for i in range(10):
        main(i*10)
    ‘‘‘

    pool = Pool()#多线程
    pool.map(main,[i*10 for i in range(10)])
时间: 2024-08-05 07:08:07

使用requests爬取猫眼电影TOP100榜单的相关文章

爬虫实战01——爬取猫眼电影top100榜单

#需求:抓取猫眼电影TOP100的电影名称.时间.评分.图片等信息,提取的结果会以文件的形式保存下来 import requests import time from lxml import etree import json import csv import codecs class MaoYanTop100Spider: #存储电影详情页的url film_page_url_list = [] #存储每个的电影信息 #film_info = {} film_info_list = [] #

python学习之抓取猫眼电影Top100榜单

目录 1 本篇目标 2 url分析 3 页面抓取 4 页面分析 5 代码整合 6 优化 参考: 近期开始学习python爬虫,熟悉了基本库.解析库之后,决定做个小Demo来实践下,检验学习成果. 1 本篇目标 抓取猫眼电影总排行榜Top100电影单 根据电影演员表统计演员上榜次数 2 url分析 目标站点为https://maoyan.com/board/4,打开之后就可以看到排行榜信息,如图所示 页面上显示10部电影,有名次.影片名称.演员信息等信息.当拉到最下面点击第二页的时候,发现url变

# [爬虫Demo] pyquery+csv爬取猫眼电影top100

目录 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 代码君 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 https://maoyan.com/board/4?offset=0 翻页操作只会改变offset偏移量,每部电影的信息都在dd标签内,使用pyquery库中的css选择器直接解析页面 代码君 css选择器直接选择和使用find()方法的区别:find()用于选择子节点,因此限定了选择的区域,速度可能要快些,直接传入''选择器可能

python爬取猫眼电影top100排行榜

爬取猫眼电影TOP100(http://maoyan.com/board/4?offset=90)1). 爬取内容: 电影名称,主演, 上映时间,图片url地址保存到mariadb数据库中;2). 所有的图片保存到本地/mnt/maoyan/电影名.png 代码: import re import pymysql as mysql from urllib import request from urllib.request import urlopen u = 'root' p = 'root'

python爬虫,爬取猫眼电影top100

import requests from bs4 import BeautifulSoup url_list = [] all_name = [] all_num = [] all_actor = [] all_score = [] class Product_url(): # 这个地方传入的url是 https://maoyan.com/board/4?offset= global url_list def __init__(self, url): self.url = url for x i

python爬取猫眼电影top100

最近想研究下python爬虫,于是就找了些练习项目试试手,熟悉一下,猫眼电影可能就是那种最简单的了. 1 看下猫眼电影的top100页面 分了10页,url为:https://maoyan.com/board/4?offset=0 我们发起请求,得到相应: 我们 我使用的是requests库,这是一个第三方的库. 2 利用正则解析爬取下的页面 当然你也可以使用xpath和bs4. 我们先看一下网页的源代码: 然后根据代码写出要匹配的正则,然后对匹配出来的数据做解析: 3 将抓到的数据写入本地文件

Python爬虫实战之Requests+正则表达式爬取猫眼电影Top100

import requests from requests.exceptions import RequestException import re import json # from multiprocessing import Pool # 测试了下 这里需要自己添加头部 否则得不到网页 headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Ge

Requwsts+正则表达式爬取猫眼电影Top100

流程框架: 抓取单页内容:利用requests请求目标站点,得到单个网页HTML代码,返回结果. 正则表达式分析:根据HTML代码分析得到电影和名称.主演.上映时间.评分.图片链接等信息. 开启循环及多线程:对多页内容遍历,开启多线程提高抓取速度. 保存至文件:通过文件的形式将内容结果保存,每一部电影一个结果一行Json字符串. 原文地址:https://www.cnblogs.com/779084229yyt/p/9692010.html

20170513爬取猫眼电影Top100

import jsonimport reimport requestsfrom bs4 import BeautifulSoupfrom requests import RequestExceptionfrom multiprocessing import Pooldef get_one_page(url): headers = {'User-Agent':'baiduspider+'} try: response = requests.get(url,headers=headers,timeo