python正则匹配抓取豆瓣电影链接和评论代码分享

yipeiwu_com6年前Python爬虫

复制代码 代码如下:

import urllib.request
import re
import time

def movie(movieTag):

    tagUrl=urllib.request.urlopen(url)
    tagUrl_read = tagUrl.read().decode('utf-8')
    return tagUrl_read

def subject(tagUrl_read):

    '''
        这里还存在问题:
        ①这只针对单独的一页进行排序,而没有对全部页面的电影进行排序
        ②下次更新添加电影链接,考虑添加电影海报
        ③需要追加列表
        ④导入到本地txt或excel中
        ⑤在匹配电影名字时是否可以同时匹配链接与名字、评分、评论组成数组
        ⑥
    '''
#正则表达式匹配电影的名字(链接)、评分与评论   
    nameURL = re.findall(r'(http://movie.douban.com/subject/[0-9.]+)\/"\s+title="(.+)"',tagUrl_read)
    scoreURL = re.findall(r'<span\s+class="rating_nums">([0-9.]+)<\/span>',tagUrl_read)
    evaluateURL = re.findall(r'<span\s+class="pl">\((\w+)人评价\)<\/span>',tagUrl_read)
    movieLists = list(zip(nameURL,scoreURL,evaluateURL))
    newlist.extend(movieLists)
    return newlist

#用quote处理特殊(中文)字符
movie_type = urllib.request.quote(input('请输入电影类型(如剧情、喜剧、悬疑):'))
page_end=int(input('请输入搜索结束时的页码:'))
num_end=page_end*20
num=0
page_num=1
newlist=[]
while num<num_end:
    url=r'http://movie.douban.com/tag/%s?start=%d'%(movie_type,num)
    movie_url = movie(url)
    subject_url=subject(movie_url)
    num=page_num*20
    page_num+=1
else:
    #使用sorted函数对列表进行排列,reverse参数为True时升序,默认或False时为降序, key=lambda还不是很明白这里的原理
    movieLIST = sorted(newlist, key=lambda movieList : movieList[1],reverse = True)
    for movie in movieLIST:
        print(movie)

time.sleep(3)

print('结束')

相关文章

Python爬虫使用代理IP的实现

Python爬虫使用代理IP的实现

使用爬虫时,如果目标网站对访问的速度或次数要求较高,那么你的 IP 就很容易被封掉,也就意味着在一段时间内无法再进行下一步的工作。这时候代理 IP 能够给我们带来很大的便利,不管网站怎么...

Python基于多线程实现抓取数据存入数据库的方法

本文实例讲述了Python基于多线程实现抓取数据存入数据库的方法。分享给大家供大家参考,具体如下: 1. 数据库类 """ 使用须知: 代码中数据表名 aces ,需要更改该数据表名...

Python爬虫包 BeautifulSoup 递归抓取实例详解

Python爬虫包 BeautifulSoup  递归抓取实例详解 概要: 爬虫的主要目的就是为了沿着网络抓取需要的内容。它们的本质是一种递归的过程。它们首先需要获得网页的内容...

python3爬虫获取html内容及各属性值的方法

今天用到BeautifulSoup解析爬下来的网页数据 首先导入包from bs4 import BeautifulSoup 然后可以利用urllib请求数据 记得要导包 impor...

Python爬取qq空间说说的实例代码

具体代码如下所示: #coding:utf-8 #!/usr/bin/python3 from selenium import webdriver import time impo...