此篇文章是根据https://mp.weixin.qq.com/s/rRtb8ATXrVxr3r5uLEhRtA这个文章的步骤进行爬取的。有兴趣的可以直接到该作者的连接查看文章。
介绍一下我的装备:
浏览器:谷歌浏览器
爬取步骤
一,到猫眼官网,电影选项,查看每个电影的连接。
选择一个电影,右击选择“检查(shift+ctrl+i)”,可以找到该电影的跳转连接。
二、对电影详情页进行初步分析
右键检查可以看到用户评分,人评分,累计票房都做了反爬虫的限制。
在开发人员工具中可以看到数字前面的class属性为stonefont,所以通过Ctrl+F找到获取文字编码的URL
得到了文字的编码之后,需要对其进行解码。作者是用pycharm来进行爬取的,我这边先试一下jupyter,表示无法安装合适的第三方包,所以我还是选择用pycharm。
因为原文中省略了一些步骤,所以刚开始看的时候的还有点懵。后来仔细阅读和尝试了一下,知道下载woff的意思是将猫眼上面的woff下载下来。直接复制粘贴上图中format('woff')漆面的连接就可以下载下来了。
---------更新2019.01.25----------
按照作者之前的代码操作,发现现在是无法运行的,所以借鉴了一下,然后又添加了自己的一些想法。
问题1:用BeautifulSoup无法爬取stonefont中的数据,爬取出来的都是空值。
解法:用正则表达式可以爬取。
问题2:每个网页中的反爬文字下载链接都是不同的,会动态改变。而且每个woff文字对应的规则也不一致。
解法:可以将woff链接保存下来。但是怎么将不同的woff规则对应到数字,暂无解决。
第一遍代码:
import requests
import time
from fontTools.ttLib import TTFont
from bs4 import BeautifulSoup
import re
import lxml
import pymysql
# 经典电影为showType=3,offset=30
# 抓取2018年上映的电影,
# 按照在网页上面点击的选项出现的链接为:https://maoyan.com/films?showType=3&sortId=1&yearId=13,且网页上面显示的为195页。
# 步骤1,遍历首页连接,得到每个影片的连接。
head = """
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9
cache-control: max-age=0
Host: maoyan.com
content-type: text/html; charset=utf-8
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
"""
# 构建请求头,可以在不同函数里构建不同的请求头
def str_to_dict(header):
header_dict = {}
header = header.split('\n')
for h in header:
h = h.strip()
if h:
k, v = h.split(':', 1)
header_dict[k] = v.strip()
return header_dict
# 获取影片的详情页
def get_url():
a = 194*30+1
num2 = 0
for i in range(0, a, 30):
# time.sleep(5)
url = 'https://maoyan.com/films?showType=3&sortId=1&yearId=13&offset=' + str(i)
host = """referer: https://maoyan.com/films?showType=3&sortId=1&yearId=13"""
header = head + host
headers = str_to_dict(header)
response = requests.get(url=url, headers=headers)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
data_1 = soup.find_all('div', {'class': 'channel-detail movie-item-title'})
data_2 = soup.find_all('div', {'class': 'channel-detail channel-detail-orange'})
urls_lib = []
num = 0
num2 += 1
for item in data_1:
# time.sleep(6)
num += 1
url_1 = item.select('a')[0]['href']
if data_2[num-1].get_t