python3爬虫爬取猫眼电影TOP100(含详细爬取思路)

待爬取的网页地址为https://maoyan.com/board/4,本次以requests、BeautifulSoup css selector为路线进行爬取,最终目的是把影片排名、图片、名称、演员、上映时间与评分提取出来并保存到文件。


初步分析:所有网页上展示的内容后台都是通过代码来完成的,所以,不管那么多,先看源代码

F12打开chrome的调试工具,从下面的图可以看出,实际上每一个电影选项(排名、分数、名字等)都被包括在dd标签中。


为了能把这些影片信息爬取出来,可以有以下两种思路。

思路一:把电影的每一个要素的列表先提取出来,类似如下:

titile = ['霸王别姬','肖申克的救赎'....],index = [1,2...],

最后从各个列表中选中对应的item拼接成一个个新的列表或字典类型,

类似如下:result = [{'title':'霸王别姬','index':'1'},{'title':'肖申克的救赎','index':'2'.....}

分析:因为要多次进行遍历,思路一的整体逻辑较混乱,容易出错

思路二:把每一个dd标签作为一个整体提取为一个列表,然后对列表的每一项(包含每部影片的各项信息)进行解析提取

分析:很明显,相对第一种思路,第二种思路就更加的清晰明了


下面通过代码来实现思路二的方式:

第一步:获取当前页的网页源代码

def get_current_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
    }
    try:
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except RequestException:
        return None

第二步:解析当前网页提取出影片信息

def parse_html(html):
    soup = BeautifulSoup(html, 'lxml')
    dd = soup.select('dd') #css选择器,select是选取所有符合条件的节点,select_one是选取第一个符合条件的节点
    for result in dd:
     #生成器的方式更省内存  
yield { 'index': result.select_one('.board-index').text, #获取影片排名 'title':result.select_one('.image-link')['title'], #获取影片名字 'image':result.select_one('.poster-default')['src'], #获取影片图片链接 'star':result.select_one('.star').text.strip(), #获取演员信息 'realeasetime':result.select_one('.releasetime').text.strip(),#获取上映时间 'score':result.select_one('.integer').text+result.select_one('.fraction').text #获取影片得分 }

第三步:将结果保存到文件

def save_to_file(content):
    with open('result.txt', 'a', encoding='utf-8') as f:   #以追加的形式写入文件
        f.write(json.dumps(content, ensure_ascii=False) + '\n')

以上实现了单页影片信息的爬取与存储,下面探索怎么实现翻页后的页面爬取

思路:既然要翻页,那就先点击下一页看看,找找规律,从下图可以看出url后面多了个?offset=10,继续翻页显示为?offset=20,最后一页显示为?offset=90,这就找到规律了,每一个url后面的url都等于页面号x10(页面号从0计数)。

得出规律之后我们开始写主函数

第四步:写主函数

def main(offset):
    url = 'https://maoyan.com/board/4?offset=' + str(offset * 10) 
    html = get_current_page(url)
    for result in parse_html(html):
        print(result)
        save_to_file(result)

第五步:写函数入口

if __name__ == '__main__':
    depth = 10
    for i in range(depth):
        main(i)

最后运行的结果:

 整个的爬取过程就是这样,完整代码查看可以点击这里

 

 

猜你喜欢

转载自www.cnblogs.com/sjfeng1987/p/9849568.html