【爬虫实战1】requests加正则表达式爬取猫眼电影top100

403错误

解决方法:添加headers信息

def get_one_page(url):
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'}
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return response.status_code
    except RequestException:
        return 'requestexception'

写文件保存中文乱码

【爬虫实战1】requests加正则表达式爬取猫眼电影top100_第1张图片
解决方法:open方法中添加encoding='utf-8’参数,write方法中添加ensure_ascii=False参数

def write_to_file(content):
    with open('result.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
        f.close()

抓取源码

import json
import re
import requests
from requests.exceptions import RequestException
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/78.0.3904.70 Safari/537.36'}
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return response.status_code
    except RequestException:
        return 'requestexception'


# 对网页进行解析
def parse_one_page(html):
    pattern = re.compile('
.*?board-index.*?>(\d+).*?title="(.*?)".*?data-src="(.*?)".*?star">(.*?)

' '.*?releasetime">(.*?)

.*?integer">(.*?).*?fraction">(.*?).*?
', re.S) items = re.findall(pattern, html) for item in items: yield { 'index': item[0], 'title': item[1], 'image': 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') f.close() def main(offset): url = 'https://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) if __name__ == '__main__': pool = Pool() pool.map(main, [i*10 for i in range(10)])

你可能感兴趣的:(【爬虫实战1】requests加正则表达式爬取猫眼电影top100)