我已经开始学习Scrapy,并尝试废弃LetterBoxd我无法集成Splash和Scrapy如何刮掉前2000页?

如何解决我已经开始学习Scrapy,并尝试废弃LetterBoxd我无法集成Splash和Scrapy如何刮掉前2000页?

import scrapy
from scrapy_splash import SplashRequest
 
class Test4basicSpider(scrapy.Spider):
    name = 'test4Basic'
    allowed_domains = ['letterboxd.com']
    start_urls = ['https://letterboxd.com/films/popular/size/small/page/1/']
    # start_urls = ['https://letterboxd.com/film/tales-from-the-darkside-the-movie/']
 
    script1 = '''
    function main(splash,args)
        splash.private_mode_enabled = false
        url = args.url
        assert(splash:go(args.url))
        assert(splash:wait(0.5))
        return {
            html = splash:html()
        }
    end
    '''
 
    def start_requests(self):
        yield SplashRequest(url='https://letterboxd.com/films/popular/size/small/page/1/',callback=self.parse,endpoint="execute",args={
            'lua_source': self.script1
        })
 
    def parse(self,response):
        for movie in response.xpath("//li[@class='listitem poster-container']"):
            movie_url = movie.xpath("(//a[@class='frame'])[1]/@href").get()
            yield scrapy.Request(
                url=f'https://letterboxd.com{movie_url}',callback=self.parse_movie,)
 
        next_page = response.xpath("//a[@class='next']/@href").get()
        if next_page:
            yield SplashRequest(
                url=f'https://letterboxd.com{next_page}',endpoint='execute',args={
                    'lua_source': self.script1
                },callback=self.parse
            )
 
    def parse_movie(self,response):
 
        yield {
            'title': response.xpath('//section[@id="featured-film-header"]/h1/text()').get(),'year': response.xpath('//small[@class="number"]/a/text()').get(),'duration': response.xpath('(//p[@class="text-link text-footer"]/text())[1]').get(),'genre': response.xpath('//div[@class="text-sluglist capitalize"]/p/a/text()').getall(),'rating': response.xpath('//a[contains(@class,"tooltip display-rating")]/text()').get(),'language': response.xpath('((//span[contains(text(),"Language")]/parent::node()/following::node())/p/a/text())[1]').get()
        }

如果我直接从任何电影URL进行刮除,我就能成功地刮除除Ratings(需要Javascript)之外的所有字段。我也尝试对分页应用一些逻辑,但是当我尝试爬网时却一无所获。该代码在哪里出错? Letterboxd的robots.txt文件可以禁止它吗,我不知道如何。

解决方法

关于下一页的问题。听起来好像需要下一页链接的启动请求。您应该考虑如何继续请求下一页链接,直到没有链接为止。

为您提供一些帮助。无需使用飞溅来获得评分。

如果您查看浏览器在检查页面时发出的请求。您已经看到有一个AJAX请求,其中包含与该评分相对应的一些HTML,正如您所建议的那样,它是由javascript加载的。

enter image description here

我倾向于复制此请求并将其粘贴到curl.trillworks.com中。将cURL命令转换为python。然后,您可以处理请求,看看是否可以在没有任何标题的情况下抓住它……

enter image description here 实际上,您甚至不需要标题/参数/ cookie来发出请求。要获取评级信息,您可以向https://letterboxd.com/csi/film/joker-2019/rating-histogram/

发送一个简单的HTTP get请求

代码示例

start_url = ['https://letterboxd.com/csi/film/joker-2019/rating-histogram/']
def parse(self,response):
    rating = response.xpath('//a[@class="tooltip display-rating"]/text()').get()

输出

3.8

对于任何电影链接,请将joker-2019替换为指定特定电影页面链接的URL的相应​​部分。

根据评论更新

您实际上几乎已经掌握了这个。您已经为下一页正确编写了代码。我认为您每个链接的XPATH选择器都有些许错误。

更新代码

for movie in response.xpath("//li[@class='listitem poster-container']"):
            movie_url = movie.xpath(".//a[@class='frame']/@href").get()
            print(movie_url)
            yield scrapy.Request(
                url=f'https://letterboxd.com{movie_url}',callback=self.parse_movie,dont_filter=True
            )

更正

  1. 请注意,它应该是.//而不是//.//搜索每个response.xpath("//li[@class='listitem poster-container']")列表项的相对路径。简单的错误,我们都错过了。

  2. 我不太了解XPATH选择器

    '(//a[@class='frame'])[1]/@href'

    我已将其更改为有效的'//a[@class='frame']/@href'

  3. 它正在过滤所有请求,因为它具有相同的基本URL letterboxd.com,因此在scrapy.Request中,必须确保dont_filter=True处理所有请求。 / p>

更新2:将Rating纳入代码

请参阅答案的主体,但这是实现。我们创建链接的部分内容,我们需要将其提供给提供评级的直方图URL。然后,我们调用一个回调来获取该评分,然后将该变量通过rating方法传递给parse_movie方法。

def parse(self,response):
        
    for movie in response.xpath("//li[@class='listitem poster-container']"):
        movie_url = movie.xpath(".//a[@class='frame']/@href").get()
        partial = movie_url.split('/')[-2]

        yield scrapy.Request(
            url=f'https://letterboxd.com{movie_url}',dont_filter=True
            )

        rating_url = f'https://letterboxd.com/csi/film/{partial}/rating-histogram/'
        yield scrapy.Request(url=rating_url,callback=self.rating)
        
        next_page = response.xpath("//a[@class='next']/@href").get()
        if next_page:
            yield SplashRequest(
                url=f'https://letterboxd.com{next_page}',endpoint='execute',args={
                    'lua_source': self.script1
                },callback=self.parse
            )

def rating(self,response):
    self.rating = response.xpath('//a[@class="tooltip display-rating"]/text()').get()

def parse_movie(self,response):
 
    yield {
            'title': response.xpath('//section[@id="featured-film-header"]/h1/text()').get(),'year': response.xpath('//small[@class="number"]/a/text()').get(),'duration': response.xpath('(//p[@class="text-link text-footer"]/text())[1]').get(),'genre': response.xpath('//div[@class="text-sluglist capitalize"]/p/a/text()').getall(),'rating': self.rating,'language': response.xpath('((//span[contains(text(),"Language")]/parent::node()/following::node())/p/a/text())[1]').get()
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-