首页 > 编程语言 >Python爬取猫眼电影榜单电影数据以及遇到问题总结

Python爬取猫眼电影榜单电影数据以及遇到问题总结

时间:2022-10-22 11:34:26浏览次数:52  
标签:__ Python self 电影 爬取 url html time print

代码

import csv
import random
import re
import time
from urllib import request

from fake_useragent import UserAgent



#定义一个爬虫类
class MaoyanSpider(object):

    #定义初始页面url
    def __init__(self):
        self.url='https://maoyan.com/board/4?offset={}'

    #请求函数
    def get_html(self,url):
        ac = ''
        ua = UserAgent()


        with open('../accept.txt', 'r') as f:
            ac = f.read()

        headers={
            'Content-Type': 'text/plain; charset=UTF-8',
            'Origin': 'https://maoyan.com',
            'Referer': 'https://maoyan.com/board/4',
            'User-Agent': str(UserAgent().random),
            'Cookie':'uuid_n_v=v1; uuid=3F4ABD90515B11ED85D65D754909B702AF37B8DA83644A4088E2E969F595441F; _lxsdk_cuid=183fb51d246c8-06c430d6eb2ef5-7b555476-d34f0-183fb51d246c8; _csrf=340d884c8d1befce8efd5f08d3a0cfe3c966cf66dec884ef3a06390c984cb7b0; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1666368787,1666401162; __mta=48668313.1666368787309.1666372933563.1666401171306.8; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1666401708; _lxsdk=3F4ABD90515B11ED85D65D754909B702AF37B8DA83644A4088E2E969F595441F; _lxsdk_s=183fd3fd1d6-237-700-88b%7C%7C21',
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        }

        req=request.Request(url=url,headers=headers)
        res=request.urlopen(req)
        html=res.read().decode()



        #直接调用解析函数
        self.parse_html(html)


    def parse_html(self,html):
        # 正则表达式
        re_bds = '<div class="movie-item-info">.*?title="(.*?)".*?<p class="star">(.*?)</p>.*?class="releasetime">(.*?)</p>'
        # 生成正则表达式对象
        pattern = re.compile(re_bds, re.S)
        # r_list: [('我不是药神','徐峥,周一围,王传君','2018-07-05'),...] 列表元组
        r_list = pattern.findall(html)
        print(html)

        self.save_html(r_list)



    def save_html(self,r_list):
        #生成文件对象
        with open('D:/桌面/PyCases/maoyan.csv','a+',newline='',encoding='utf-8-sig') as f:
            headfile=['片名','主演','上映时间']
            writer=csv.DictWriter(f,fieldnames=headfile)
            writer.writeheader()


            for r in r_list:
                name=r[0].strip()
                star=r[1].strip()[3:]
                time=r[2].strip()[5:15]
                writer.writerow({'片名':name,'主演':star,'上映时间':time})
                print(name,star,time)

    def run(self):
        print('开始抓取.....')
        begin=time.time()
        for offset in range(0,21,10):
            print(offset)
            url=self.url.format(offset)
            self.get_html(url)
            time.sleep(random.uniform(2,3))

        end=time.time()
        print('抓取完成')
        print('执行时间:%.2f' % (end - begin))

if __name__ == '__main__':
    try:
        spider = MaoyanSpider()
        spider.run()
    except Exception as e:
        print("错误",e)

所遇到的问题

1. 爬取网页中遇到认证的问题

解决办法:
在请求头中加入‘Accept’,‘Cookie’
image

2.爬取数据生成csv表格时数据覆盖的问题

解决办法:
with open('w')改为with open('a+')
'a+'为追加数据
'w'为写入数据

image

下一步需要解决的问题

在爬取过程中,网页的反爬措施为需要滑动验证,需要手动操作才能继续爬取

image

标签:__,Python,self,电影,爬取,url,html,time,print
From: https://www.cnblogs.com/LiSymbol/p/16815662.html

相关文章

  • python打印菱形
    #_*_encoding:utf-8_*_@author:tyhery2018/9/6defprintStar(intNum):s="*"spaceLength=intNumblockCount=int(intNum/2+1)......
  • Python Easyocr 图片文字识别
    前段时间做了车牌识别相关的内容分享,参看:​​车牌识别(1)-车牌数据集生成​​​​车牌识别(2)-搭建车牌识别模型​​今天给大家分享一个简单的OCR文本识别工具:easyocr。这个模块......
  • Python Easyocr 图片文字识别
    前段时间做了车牌识别相关的内容分享,参看:​​车牌识别(1)-车牌数据集生成​​​​车牌识别(2)-搭建车牌识别模型​​今天给大家分享一个简单的OCR文本识别工具:easyocr。这个模块......
  • 建议收藏| 学python的看过来,Python 史上最全第三方库收集
    发现一个宝藏网站:GitHub上有一个Awesome-XXX系列的资源整理,这个系列以“全”闻名,但凡是有一定知识度的领域、语言、框架等,都有自己的awesome-xxx系列的项目。今天......
  • 快学起来!python入门自学必看
    记得刚开始学python的时候,各种买书各种找资料,最后发现资料找了一大堆,但都是东一块西一块,内容不全且不系统,无意间发现这个宝藏网站,真的是太全了,当作工具书,时不时的翻翻,总会......
  • #yyds干货盘点# 盘点一个Python安装库的时候遇到的一个小问题
    大家好,我是皮皮。一、前言前几天在Python铂金交流群【Crazy】问了一个​​Python​​基础的问题,提问截图如下:报错的截图如下:二、实现过程看上去确实没啥问题,因为库都已经存......
  • 让 Python 程序定时执行的 8 种姿势~
     八种用Python实现定时执行任务的方案,一定有你用得到的!_嗨学编程的博客-CSDN博客让Python程序定时执行的8种姿势~-文章详情(itpub.net)......
  • 力扣121(java&python)-买卖股票的最佳时机(简单)
    题目:给定一个数组prices,它的第 i个元素 prices[i]表示一支给定股票第i天的价格。你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子卖出该股票。......
  • python里面用append把一个数组压到另一个数组里面,原来的数组如果再append东西,后来的数
    在python里有一个非常烦人的问题就是给数组填充新值时,假如用append的方法,最终填充进数组的不是实际的值,而是类似于一个指针(比喻一下,和指针的差别还是很大的)如果原数组继续a......
  • Python字符串与数组相互转换
    Python中有join()和os.path.join()两个函数,具体作用如下:join():连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串os.path.jo......