使用requests库和正则表达式爬取猫眼电影前100

import requests
import re
import json
import time
from requests.exceptions import RequestException def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
response = requests.get(url,headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern,html)
for item in items:
yield {
'index':item[0],
'image':item[1],
'title':item[2].strip(),
'actor':item[3].strip()[3:] if len(item[3]) > 3 else '',
'time':item[4].strip()[5:] if len(item[4]) > 5 else '',
'score':item[5].strip() + item[6].strip()
} def write_to_file(content):
with open('result.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n')
def main(offset):
url = 'https://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
# print(html)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__ == '__main__':
for i in range(10):
main(offset=i*10)
time.sleep(1)

使用requests库和Beautifulsoup库爬去猫眼电影前100

import requests
from bs4 import BeautifulSoup def gethtmlpage(url):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None def parsehtmlpage(html):
soup = BeautifulSoup(html, 'lxml')
a = soup.select('.movie-item-info a')
return a def write_to_file(content):
with open('result.txt', 'a', encoding="utf-8") as f:
f.writelines(content + '\n') def main(url):
html = gethtmlpage(url)
title = parsehtmlpage(html)
for i in range(0, len(title)):
write_to_file(title[i].string) if __name__ == '__main__':
for i in range(10,100,10):
url = "https://maoyan.com/board/4?offset=%d" % i
main(url)

使用Beautiful库和requests库爬去:

import requests
from bs4 import BeautifulSoup
import bs4 def gethtmlpage(url):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except ConnectionError:
return "网络链接出错"
except:
return "未知错误" def parsehtmlpage(html):
soup = BeautifulSoup(html, 'lxml')
ol = soup.select("ol.grid_view")
li = ol[0].select('li')
movie=[]
for i in range(0, len(li)):
index = li[i].select(".pic em")[0].string
title = li[i].find("span", attrs={'class', 'title'}).string
rating_num = li[i].find("span", attrs={'class', 'rating_num'}).string
lianjie = li[i].select(".hd a")[0].get('href')
if isinstance(li[i].find("span", attrs={'class', 'inq'}), bs4.element.Tag):
inq = li[i].find("span", attrs={'class', 'inq'}).string
else:
inq = "没有简介"
movie.append([index, title, rating_num, lianjie, inq])
return movie def writetofile(content):
with open('result.csv', 'a', encoding='utf-8') as f:
f.write(content) def main(url):
html = gethtmlpage(url)
movie = parsehtmlpage(html)
for i in range(0, len(movie)):
writetofile("{0:^5}\t{1:{5}^10}\t{2:^10}\t{3:^40}\t{4:<10}\n".format(movie[i][0], movie[i][1], movie[i][2], movie[i][3], movie[i][4], chr(12288))) if __name__ == '__main__':
writetofile("{0:^5}\t{1:{5}^10}\t{2:^8}\t{3:^40}\t{4:<10}\n".format("排名", "电影名", "评分", "链接", "一句话介绍电影", chr(12288)))
for i in range(0, 10):
url = "https://movie.douban.com/top250?start={}".format(i*25)
main(url)

python应用-爬取猫眼电影top100的更多相关文章

  1. 爬虫系列(1)-----python爬取猫眼电影top100榜

    对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天在整理代码时,整理了一下之前自己学习爬虫的一些代码,今天先上一个简单的例子,手把手教你入门Python爬虫,爬取 ...

  2. python 爬取猫眼电影top100数据

    最近有爬虫相关的需求,所以上B站找了个视频(链接在文末)看了一下,做了一个小程序出来,大体上没有修改,只是在最后的存储上,由txt换成了excel. 简要需求:爬虫爬取 猫眼电影TOP100榜单 数据 ...

  3. PYTHON 爬虫笔记八:利用Requests+正则表达式爬取猫眼电影top100(实战项目一)

    利用Requests+正则表达式爬取猫眼电影top100 目标站点分析 流程框架 爬虫实战 使用requests库获取top100首页: import requests def get_one_pag ...

  4. 50 行代码教你爬取猫眼电影 TOP100 榜所有信息

    对于Python初学者来说,爬虫技能是应该是最好入门,也是最能够有让自己有成就感的,今天,恋习Python的手把手系列,手把手教你入门Python爬虫,爬取猫眼电影TOP100榜信息,将涉及到基础爬虫 ...

  5. 40行代码爬取猫眼电影TOP100榜所有信息

    主要内容: 一.基础爬虫框架的三大模块 二.完整代码解析及效果展示 1️⃣  基础爬虫框架的三大模块 1.HTML下载器:利用requests模块下载HTML网页. 2.HTML解析器:利用re正则表 ...

  6. # [爬虫Demo] pyquery+csv爬取猫眼电影top100

    目录 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 代码君 [爬虫Demo] pyquery+csv爬取猫眼电影top100 站点分析 https://maoyan.co ...

  7. 用requests库爬取猫眼电影Top100

    这里需要注意一下,在爬取猫眼电影Top100时,网站设置了反爬虫机制,因此需要在requests库的get方法中添加headers,伪装成浏览器进行爬取 import requests from re ...

  8. Python爬虫项目--爬取猫眼电影Top100榜

    本次抓取猫眼电影Top100榜所用到的知识点: 1. python requests库 2. 正则表达式 3. csv模块 4. 多进程 正文 目标站点分析 通过对目标站点的分析, 来确定网页结构,  ...

  9. # 爬虫连载系列(1)--爬取猫眼电影Top100

    前言 学习python有一段时间了,之前一直忙于学习数据分析,耽搁了原本计划的博客更新.趁着这段空闲时间,打算开始更新一个爬虫系列.内容大致包括:使用正则表达式.xpath.BeautifulSoup ...

随机推荐

  1. matplotlib 绘图报错 RuntimeError: Invalid DISPLAY variable

    ssh 远程登录 Linux 服务器使用 matplotlib.pyplot 绘图时报错 原因: matplotlib 在 windows 下的默认 backend 是 TkAgg:在 Linux 下 ...

  2. Python学习:经典编程例题

    九九乘法表 ,): ,i+): print(i,'*',j,'=',i*j,end='\t') print() 水仙花数问题描述:100-999之间每个数的立方相加等于原数例如:153=1 ^ 3 + ...

  3. graph_base_pic_segmentation里面的细节和代码

    https://github.com/zhangbo2008/graph_base_pic_segmentation_analyzing/blob/master/README.md

  4. Koa源码分析(三) -- middleware机制的实现

    Abstract 本系列是关于Koa框架的文章,目前关注版本是Koa v1.主要分为以下几个方面: Koa源码分析(一) -- generator Koa源码分析(二) -- co的实现 Koa源码分 ...

  5. Maven学习 九 maven热部署

    第一步:配置tomcat的manager-script角色 点击tomcat的默认项目root的欢迎页面的Manager App 刚开始是没有用户名与和密码的,直接点击取消 出现如下的一张图片,图片中 ...

  6. Appium+Python自动化 1 环境搭建(适用windows系统-Android移动端自动化)

    一.安装并配置 java jdk ①下载 java jdk后 安装,安装完成后,配置环境变量 打开计算机->系统属性->高级系统设置->环境变量->新建(系统变量),如图所示: ...

  7. 创建Gitblit本地服务器(For windows )01

    1.先下载gitblit  貌似需要FQ,百度云链接https://pan.baidu.com/s/1WUtBswj5TkFFcd_hiFFCcw,提取码: xr9n .因为gitblit是基于jav ...

  8. 20155312 张竞予 Exp9 Web安全基础

    Exp9 Web安全基础 目录 基础问题回答 (1)SQL注入攻击原理,如何防御 (2)XSS攻击的原理,如何防御 (3)CSRF攻击原理,如何防御 实践过程记录 WebGoat准备工作 1.XSS攻 ...

  9. Redis与SpringBoot整合

    添加Redis相关jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...

  10. spring BeanWrapperImpl方便的嵌套属性(list)操作

    beans 包主要提供了接口和类用于处理java beans.     其中最主要的接口是BeanWrapper:     Spring 的中心接口,用于访问javabeans 的低层操作.默认实现为 ...