主要步骤有:
访问网站,获取页面源码
解析页面,得到想要的数据
循环爬取多个页面
把数据写入本地文件
1. 分析需要爬取的页面结构
访问猫眼电影。观察页面,会看到首页上有排名前十的电影信息。
找到页面中的分页,点击不同的页码。对比不同页面url的差别,会发现不同的分页是以offset参数作为区分的。
因为每个页面都显示10条电影信息,所以offset是以10作为偏移量的。所以第1页的offset=0,第2页的offset=10,第3页的offset=20,后面的页面也是以此类推。
2. 抓取首页
2.1 获取首页的源码
首先定义一个方法,请求页面,并获得页面源码:
import requests
from requests.exceptions import RequestException
headers = {'user-agent':'mozilla/5.0'}
def get_one_page(url):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def main():
url = 'https://maoyan.com/board/4'
html = get_one_page(url)
print(html)
if __name__ == '__main__':
main()
在打印结果中,可以看到页面的源码已经返回。
获取到的源码中,有很多的信息不是我们需要的,这时候,需要把有用的信息提取出来。
2.2 使用正则提取信息
使用谷歌浏览器的开发者工具查看页面的源代码,可以发现我们需要的信息都包含在标签中。
排名信息包含在class为board-index的i标签中;
片名信息包含在class为name的p标签内的a标签中;
主演姓名包含在class为star的p标签中;
上映日期包含在class为releasetime的p标签中;
评分分别包含在class为integer和fraction的i标签中;
电影封面图在class为board-img的img的src属性中;
因此,可以写一个正则表达式来提取一个电影的上述信息:
pattern = re.compile('
.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name.*?(.*?)''
.*?star">(.*?).*?releasetime">(.*?).*?score.*?''integer">(.*?).*?fraction">(.*?).*?
', re.S)items = re.findall(pattern, html)
把上面的正则表达式加入到代码中:
import re
import requests
from requests.exceptions import RequestException
headers = {'user-agent':'mozilla/5.0'}
def get_one_page(url):
try:
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('
.*?board-index.*?>(\d+).*?da