分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

关于html的多行匹配,正则re.S的使用(爬取豆瓣电影短评)

发布时间:2023-09-06 01:18责任编辑:赖小花关键词:正则

参考链接:http://www.python(tab).com/html/2017/pythonhexinbiancheng_0904/1170.html(去除括号)

       http://blog.csdn.net/eastmount/article/details/51082253

首先本文参考了上述两篇文章,爬取豆瓣电影栏目上“看不见的客人短评”,并将其导入cvs。

关于正则匹配多行html,实际上需要在原有基础上加入re.S。

这样,每行行末尾将通过“\n+空格”的形式呈现出来。

而实际上匹配可以通过.*?直接过滤掉。

详情可看第13行。

另说python的pandas模块,使用DataFrame的to_cvs导入还需要进行编码转换,避免乱码。

 1 #coding=utf-8 2 import requests 3 import re 4 import pandas as pd 5 headers={ 6 ????‘User-Agent‘:‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36‘, 7 ????‘Host‘:‘movie.douban.com‘ 8 ????} 9 cookies={‘Cookie‘:‘你自己的COOKIE‘}10 url=‘https://movie.douban.com/subject/26580232/comments?status=P‘11 html=requests.get(url,headers=headers,cookies=cookies)12 reg=re.compile(r‘<a href="(.*?)&amp;status=P".*?class="next">‘)13 ren=re.compile(r‘<span class="comment-info">.*? class="">(.*?)</a>.*?<span>.*?title="(.*?)"></span>.*?<span.*? title="(.*?)">.*?<p class="">(.*?)\n‘,re.S)14 while html.status_code==200:15 ????url_next=‘https://movie.douban.com/subject/26580232/comments‘+re.findall(reg,html.text)[0]16 ????keren=re.findall(ren,html.text)17 ????data=pd.DataFrame(keren)18 ????print(data)19 ????print(url_next)20 ????data.to_csv(‘/Users/b1ancheng/Desktop/kerenduanping.csv‘,header=False,index=False, mode=‘a+‘,encoding="utf_8_sig")21 ????data=[]22 ????keren=[]23 ????html=requests.get(url_next,headers=headers,cookies=cookies)

 望兄多提意见,共同进步。

关于html的多行匹配,正则re.S的使用(爬取豆瓣电影短评)

原文地址:http://www.cnblogs.com/b1ancheng/p/7680282.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved