Python爬虫
这个网站对爬虫设置了重重阻碍
1、查看多页数据需要用户登录
2、奇怪的登录验证码
3、电影票房是一张图片
步骤
在开始爬虫前我们一步一步的解决阻碍
1、权限问题
在未登录时获取多页数据会让我们先登录,当我们在浏览器登录过后,使用python读取到的网页数据还是登录页的代码
我们都知道浏览器向服务器发送请求时都会带上请求头,我们用python直接爬取网页源码时并没有设置请求头,所以服务器并不认识我们,认为我们没有登录。所以只要我们正确的设置了请求头就能正常获取数据了
获取请求头中的cookie(需要先登录)
设置cookie后便能正确的获取网页数据
spider.py
# -*- coding: utf-8 -*-
# @File : spider.py
import requests
from bs4 import BeautifulSoup
import xlwt
'''
http://58921.com/alltime/2018
年份票房排行榜
1995 - 2021
'''
base_url = "http://58921.com"
year_url = "http://58921.com/alltime/"
all_url = "http://58921.com/alltime?page="
headers = {
# Cookie 登录验证
"Cookie":"这里是登录后获取到的cookie",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3947.100 Safari/537.36",
"Upgrade-Insecure-Requests":"1",
}
def get_html(url,encoding):
response = requests.get(url,headers=headers)
if response.status_code == 200:
# 判断请求是否成功
response.encoding = encoding
return response.text
else:
return None
def spider_year_list(url):
'''
根据url爬取排行榜 'http://58921.com/alltime/2019?page=1' 第二页
每一个年份的数据
:return:
'''
year = url.split("/alltime/")[1]
year_list = []
# 获取页数
html = get_html(url,encoding="utf-8")
soup = BeautifulSoup(html, "html.parser")
item_list = soup.find("div",class_="item-list")
if item_list is not None:
pager_number = item_list.find("li", class_="pager_count").find("span",class_="pager_number").get_text()
page = int(pager_number.split("/")[1])
else:
page = 1
for i in range(