【发布时间】: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