python爬取猫眼电影排行榜

試著忘記壹切 提交于 2019-12-21 05:18:29
import requests
import re
import json

#抓取首页
def get_one_page(url):
    headers = {#模拟浏览器
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)\
             AppleWebKit/537.36 (KHTML, like Gecko)\
             Chrome/65.0.3325.162 Safari/537.36'
    }
    response = requests.get(url,headers=headers)#模拟进入网页
    if response.status_code == 200:
        return response.text#响应成功则打印源代码
    return None


def parse_one_page(html):
#正则提取    
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
                         + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
                         + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
    items = re.findall(pattern, 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]
        }#用for循环成功提取出电影的各种内容(演员,评分等等)并将其赋值为字典,形成结构化数据。

def write_to_file(content):
#此处的content参数是一个电影的提取结果,是一个字典。
    with open('result.txt','a',encoding='utf-8') as f:
        print(type(json.dumps(content)))
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
#write_to_file(content)将提取的结果写入文件,调用dumps()方法实现字典的序列化,
#并指定ensure_ascii参数为False,这样保证结果是中文形式而不是Unicode编码。

def main(offset):
    global url,html
    url = 'http://maoyan.com/board/4?offset=' + str(offset)
    html = get_one_page(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)
#实现main()方法来调用前面实现的方法,将单页的电影结果写入到文件,接收一个offset值作为偏移量。

if __name__ == '__main__':
    for i in range(10):
        main(offset=i*10)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!