#准备工作
1.python版本3.8
2.pip install selenium
:由于斗鱼上的很多关键数据都是通过ajax请求来获取的,所以需要安装selenium来控制浏览器点击
3.谷歌浏览器+与之对应chromedriver
:火狐浏览器也可以不过笔者用的是谷歌版的
4.安装scrpay框架
目前项目已在github上想要源码的可以去git
(https://github.com/feichechuanyuelianmeng/douyu-album)
#代码分析
#这是spider类的具体代码*
import scrapy
import json
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import os
import time
from scrapy_demo.douyu.douyu.items import DouyuItem
# import selenium.webdriver.remote.webelement.WebElement
#主爬虫
class PicParseSpiderSpider(scrapy.Spider):
#下面最主要参数start_urls是打开斗鱼颜值模块的主页爬虫将从这里爬取数据
name = 'pic_parse.spider'
allowed_domains = ['www.douyu.com']
start_urls = ["https://www.douyu.com/g_yz"]
def __init__(self):
self.driver = webdriver.Chrome(executable_path=r"D:\programs\chrome_driver\chromedriver.exe")
#爬虫获取start_urls后从下面parse进入进行解析函数
def parse(self, response):
try:
self.driver.get(self.start_urls[0])
# urls用来存放所有 主播房间的链接
urls = []
# 获得主页面中的页数page,page的数值反映了共有多少页主播正在播出
# self.driver.find_elements_by_xpath("/html/body/section/main/section[2]/div[2]/ul/li")
try:
element = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located
((By.XPATH, "/html/body/section/main/section[2]/div[2]/div/ul/li[last()-1]")))
page = int(element.text)
except:
print("没有下一页了或者没有加载成功")
try:
# # 这个循环通过selenium控制浏览器不断点击 下一页按钮
for i in range(page):
time.sleep(1)
li_lsit = self.driver.find_elements_by_xpath("/html/body/section/main/section[2]/div[2]/ul/li")
# test_num来测试的可以注销
test_num = 1
# 这个循环用来循环遍历当前页面所有主播房间地址
for li in li_lsit:
try:
url = li.find_element_by_xpath("./div/a[1]").get_attribute("href")
# print("第{}页的url:".format(i + 1) + url)
# print("正在爬取第:{}页总共{}页主播房间的url".format((i+1),(page+