美文网首页python爬虫学习笔记
用requests+正则爬取猫眼电脑top100记录学习

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

作者: NewForMe | 来源:发表于2018-07-18 00:09 被阅读0次
知识点整理:
  • 1 因为猫眼已经进行了简单的防爬,不能直接用requests.get(url)请求url,会被猫眼限制,需要增加一个请求头,用requests.get(url,headers=headers)即可;
    例如:
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"}
  • 2 编写正则表达式的时候,用re.compile(pattern,re.S),pattern为正则表达式,re.S表示 . 能匹配任意字符,包括换行符,空格,因为html页面代码都可能有一些换行符,制表符什么之类的,所以一定要加上re.S
  • 3 用正则整理出我们想要的信息后,正则生成的数据是一个列表,这个数据格式不太方便,所以最好将其生成一个字典,此处使用了yield将方法变成一个生成器,然后用for循环这个生成器,读取数据,生成器的好处就是动态分配内存,不用事先固定分配好内存,需要的时候才进行读取,有关yield的用法可以,下次整理一篇文章纪录一下
  • 4 将数据写入文件时候还有注意:
    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,这样文件才能写中文

  • 5 简单利用多进程提高一点爬取速度,因为数据量不大,所以测试的效率是由1.8s提高到1.3s,下次爬取数据量大的时候,有IO阻塞的时候可以深度用一下协程来提高效率。
  • 6 完整代码:
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)

相关文章

网友评论

    本文标题:用requests+正则爬取猫眼电脑top100记录学习

    本文链接:https://www.haomeiwen.com/subject/jljnpftx.html