使用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. 关于四种语言中substring()方法参数值的解析

    1.关于substring(a,b)Js var str="bdqn"; var result=str.substring(1,2); alert(result); 第一个参数:开 ...

  2. vs2015 行数统计

    ctrol+shift+f  正則查找 b*[^:b#/]+.$

  3. python语法之函数2

    高阶函数: def f(n): return n*n def foo(a,b,func): func(a)+func(b) ret=func(a)+func(b) return ret foo(1,2 ...

  4. ConcurrentDictionary

    ConcurrentDictionary ConcurrentDictionary一大特点是线程安全,在没有ConcurrentDictionary前 在多线程下用Dictionary,不管读写都要加 ...

  5. FTP模式简式:PORT/PASV/EPRT/EPSV

    简介 常见FTP有两种模式:PORT(主动模式).PASV(被动模式). 而EPRT/EPSV模式出现的原因是FTP仅仅提供了建立在IPv4上进行数据通信的能力,它基于网络地址是32位这一假设.但是, ...

  6. VS2017 带参数启动调式程序

    有些程序,比如FFPlay,需要传递命令行参数才能运行想要的功能,比如字幕, ffplay -vf subtitles=mv.mkv mv.mkv 参数是 -vf subtitles=mv.mkv m ...

  7. 软件光栅器实现(二、VS和PS的运作,法线贴图,切空间的计算)

    二.软件光栅器的VS和PS的输入.输出和运作,实现法线贴图效果的版本.转载请注明出处. 这里介绍的VS和PS是实现法线映射的版本,本文仅介绍实现思路,并给出代码供参考.切空间计算.光照模型等相关公式不 ...

  8. docker + mysql安装sonarqube

    docker sonarqube地址:https://hub.docker.com/_/sonarqube docker mysql地址:https://hub.docker.com/_/mysql ...

  9. Codeforces Educational Codeforces Round 44 (Rated for Div. 2) F. Isomorphic Strings

    Codeforces Educational Codeforces Round 44 (Rated for Div. 2) F. Isomorphic Strings 题目连接: http://cod ...

  10. CSS伪类的理解

    因为之前一直对css伪类没有过多的了解,在网上看到一段css代码,不能理解 a:hover span.title{ color:red; ......... } 现通过查询css手册,其实css伪类只 ...