【初学python爬虫02】Python3用Requests+正则表达式爬取豆瓣电影Top250

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32958797/article/details/84877391
import requests
from requests.exceptions import RequestException
import re
import json
# from multiprocessing import Pool
#获取页面信息
def get_htmls(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None
#正则表达式获取相关数据
def get_info(htmls):
    pattern = re.compile('<div class="item">.*?<em.*?>(\d+)</em>.*?<img'
+'.*?src="(.*?)".*?title">(.*?)</span>.*?<br>(.*?)</p>.*?average">(.*?)'
+'</span>.*?inq">(.*?)</span>', re.S)
    items = re.findall(pattern, htmls)
    for item in items:
        yield {
            'index': item[0],
            'image': item[1],
            'title': item[2],
            'type':  item[3].strip(),
            'score': item[4],
            'quote': item[5]
        }
#保存为txt文本      
def save_txt(content):
    with open('DBMovie.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
        f.close()

def main(lists):
    url = 'https://movie.douban.com/top250?start=' + str(lists)
    htmls = get_htmls(url)
    for item in get_info(htmls):
        save_txt(item)
        print(item)

if __name__ == '__main__':
    for i in range(10):
        main(i*25)
    #提供指定数量的进程池,新的请求提交,进程池未满则创建新的进程
    # pool = Pool()
    # pool.map(main, [i*25 for i in range(10)])

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_32958797/article/details/84877391