python简单爬虫实例之猫眼网Top100数据抓取

现在已经大三了,之前学了好多好多东西,因为数学建模的原因开始接触matlab和python。因为对数学比较感兴趣,所以打算以后往人工智能方向发展,所以现在开始对python语言进行训练。

简述:对猫眼网Top100的电影都进行抓取

操作系统:macOS Mojave 10.14.3

使用工具:PyCharm

首先以两个简单的例子对网页数据进行抓取、存储为例,了解爬虫

过程:构建URL -> 访问URL -> 抓取网页代码 -> 构建存放文件目录 -> 存放抓取的文件

单独抓取猫眼网top100首页:

https://maoyan.com/board/4

from urllib.request import urlopen

url = 'https://maoyan.com/board/4'
response = urlopen(url)
html= (response.read().decode())
#maoyan为程序所在文件夹下的存放文件的目录名称,此格式路径为Mac系统下,其他系统请自行调整
file_name='maoyan/index.html'
#文件存储方法1.此方法打开文件后需要手动关闭文件
file=open(file_name,'w',encoding='UTF-8')
file.write(html)
file.close


'''
#文件存储方法2.此方法不需要手动关闭,由程序结束时自动关闭
with open(file_name,'w',encoding='UTF-8') as file
    file.write(html)


'''

抓取猫眼网top100所有网页:

https://maoyan.com/board/4?offset=0

https://maoyan.com/board/4?offset=10

https://maoyan.com/board/4?offset=20

......规律显而易见

循环十次即可对该网页进行完成抓取

from urllib.request import urlopen
def get_one_page(x):
    #字符串的格式化处理: {}占位符表示未知的参数,后面会补上
    url = 'https://maoyan.com/board/4?offset={}'.format(x*10)
    #第二种方法:url = 'https://maoyan.com/board/4?offset=%d'%(x*10)
    response = urlopen(url)
    return (response.read().decode())
def save_one_page(x,html):
    file_name='maoyan/page_{}.html'.format(i+1)
    file=open(file_name,'w',encoding='UTF-8')
    file.write(html)
    file.close
'''
with open(file_name,'w',encoding='UTF-8') as file
    file.write(html)


'''


    #__name__内置变量,系统已经定义的:当执行当前文件时,值为__main__,否则为其他引用模块名
if __name__=='__main__':
    #get_one_page(0)
    i=0
    while i<10:
        html=get_one_page(i)
        save_one_page(i,html)
        i=i+1

这样即可完成对猫眼网top100所有网页数据进行抓取。

本文中作为爬虫入门文章,仅介绍抓取网页内容以及存储该内容,对于存储的内容,我们可以采取正则切割的方式提取我们所需要的内容,其他内容讲再后续的帖子中介绍。

猜你喜欢

转载自blog.csdn.net/RHJlife/article/details/87597707