python爬虫学习笔记

用requests+正则爬取猫眼电脑top100记录学习

2018-07-18  本文已影响0人  NewForMe
知识点整理:
headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"}
    with open('result.txt','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')

ensure_ascii=Falseencoding='utf-8'表示生成json不需要进行ascii编码,以及写文件时候用utf-8,这样文件才能写中文

import time
import requests
from requests.exceptions import RequestException
import re
import json
from multiprocessing import Pool

def get_one_page(url):
    #请求头,将此请求欺骗服务器为浏览器请求
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"}
    response = requests.get(url,headers=headers)
    try:
        if response.status_code==200:
            return response.text
        return None
    except RequestException:
        return None

def parse_one_page(html):
    #预先编译正则表达式,用来获取想要的信息,re.S的作用是为了让 . 能匹配任意字符,包括换行符,空格,如果不加re.S则不能匹配
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S)

    result = re.findall(pattern,html)
    for item in result:
        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(content):
    with open('result.txt','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')
        #ensure_ascii=False,encoding='utf-8'表示生成json不需要进行ascii编码,以及写文件时候用utf-8,这样文件才能写中文

def main(i):
    url = 'http://maoyan.com/board/4?offset='+str(i)
    html = get_one_page(url)
    #print(html)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)

if __name__ == '__main__':
#普通爬取
    # start_time = time.time()
    # for i in range(10):
    #     main(i*10)
    # end_time = time.time()
    # print(end_time-start_time)

#多进程爬取
    start_time = time.time()
    pool = Pool()
    pool.map(main,[i*10 for i in range(10)])
    end_time = time.time()
    print(end_time - start_time)
上一篇 下一篇

猜你喜欢

热点阅读