【问题标题】:not able to apply (filter)if else condition [duplicate]如果其他条件无法应用(过滤)[重复]
【发布时间】:2021-10-31 13:45:15
【问题描述】:

我使用scrapy进行网页抓取,我可以抓取所有元素,但我的目标是获取所有评论大于 50 的名称,我不知道我缺少哪里

import scrapy


class TripadSpider(scrapy.Spider):
    name = 'tripad'
    allowed_domains = ['www.tripadvisor.in']
    start_urls = ['https://www.tripadvisor.in/Restaurants-g304554-c33-Mumbai_Maharashtra.html']
    first = 'https://www.tripadvisor.in/'

    def parse(self, response):
        for i in response.xpath("//div[@class='_2Q7zqOgW Vt o']"):
            rating = str(i.xpath(".//span[@class='w726Ki5B']/text()").get())

            if rating >= '50':
                title = i.xpath(".//a[@class='_15_ydu6b S5 H4 Cj b']/text()").getall()
                yield {
                    'title':title,
                    'rating':rating
                }
            elif rating == 'None':
                continue

        next_page = response.xpath("//a[@class='nav next rndBtn ui_button primary taLnk']/@href").get()
        if next_page:
            sequence = (self.first,next_page)
            nexturl = ''.join(sequence)
            yield scrapy.Request(url=nexturl,callback=self.parse)

谁能帮帮我

【问题讨论】:

  • rating 转换为 int , if int(rating) >= 50:
  • ValueError: int() 基数为 10 的无效文字:'1,076 出现此错误
  • 在你的 python 控制台中试试这个rating = ''.join('1,076'.split(',')) 在这里你将值 1,076 拆分为一个数组 ['1', '076'] 然后将其连接回来,没有空格。您必须检查评级字符串是否包含逗号,因为这可能会引发错误。也许使用尝试 - 除了设置评级。然后你只需要把这个字符串解析为一个整数!
  • 感谢@sittsering 它正在使用这个stackoverflow.com/questions/5188792/…
  • @sb_ 不会这样做,即“101”通过字符串比较小于“50”。

标签: python web-scraping scrapy


【解决方案1】:

用小数替换逗号

if type(eval(rating)) == int or type(eval(rating)) == float:
    rating_string_decimal = rating.replace(',','.')
    val = float(rating_string_decimal )
    if round(rating_string_decimal)>= 50:
          title = i.xpath(".//a[@class='_15_ydu6b S5 H4 Cj b']/text()").getall()
                yield {
                    'title':title,
                    'rating':rating
                }
elif rating == 'None':
    continue

【讨论】:

  • 伙计,它工作不正常
  • 现在检查我更新代码
  • dpaste.org/wrnu 这对我有用
猜你喜欢
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多