我正在使用下面的代码从网页上抓取汽车的名称、地址和数量。
但是,汽车数量时常会出现空值。让我们假设在下面的示例中,第 8 个经销商返回的汽车数量为空,因此返回的列表类似于:
名称 = a,b,c,d,e,f,g,h,i,j
地址 = aa,bb,cc,dd,ee,ff,gg,hh,ii,jj
汽车 = 1,2,3,4,5,6,7,9,10
其中地址 aa 的经销商 a 有 1 辆汽车,地址 bb 的经销商 b 有 2 辆汽车等,但由于地址 hh 的经销商 h 的汽车值为空,因此会被跳过,代码认为经销商 h 有 9 辆汽车,所以经销商 i 和地址 ii 有 10 辆汽车,因此地址 jj 的经销商 j 被错过,因为汽车列表已用完。
因此,如果代码返回 cars 的空值,我该如何将其替换为 0?因此,在上面的示例中,经销商 h 和地址 hh 将拥有 0 辆汽车,因此地址 ii 处的经销商 i 拥有 9 辆汽车,地址 jj 处的经销商 j 将拥有 10 辆汽车
import scrapy
from autotrader.items import AutotraderItem
class AutotraderSpider(scrapy.Spider):
name = "autotrader"
allowed_domains = ["autotrader.co.uk"]
start_urls = ["https://www.autotrader.co.uk/car-dealers/search?advertising-location=at_cars&postcode=m43aq&radius=1500&forSale=on&toOrder=on&sort=with-retailer-reviews&page=822"]
def parse(self, response):
for sel in response.xpath('//ul[@class="dealerList__container"]'):
names = sel.xpath('.//*[@itemprop="legalName"]/text() ').extract()
names = [name.strip() for name in names]
addresses = sel.xpath('.//li/article/a/div/p[@itemprop="address"]/text()').extract()
addresses = [address.strip() for address in addresses]
carss = sel.xpath('.//li/article/a/div/p[@class="dealerList__itemCount"]/span/text()').extract()
carss = [cars.strip() for cars in carss]
result = zip(names, addresses, carss)
for name, address, cars in result:
item = AutotraderItem()
item['name'] = name
item['address'] = address
item['cars'] = cars
yield item
最佳答案
你的选择器循环有点困惑。
这里循环浏览未排序的列表,其中每个年龄只有一个:
for sel in response.xpath('//ul[@class="dealerList__container"]'):
您想要的是循环遍历所有列表项:
for sel in response.xpath('//li[@class="dealerList__itemContainer"]'):
如果以这种方式循环,您可以获得每个单独列表项的名称、地址:
for sel in response.xpath('//li[@class="dealerList__itemContainer"]'):
names = sel.xpath('.//*[@itemprop="legalName"]/text() ').extract()
names = [name.strip() for name in names]
addresses = sel.xpath('.//article/a/div/p[@itemprop="address"]/text()').extract()
addresses = [address.strip() for address in addresses]
carss = sel.xpath('.//article/a/div/p[@class="dealerList__itemCount"]/span/text()').extract()
carss = [cars.strip() for cars in carss]
item = AutotraderItem()
item['name'] = name
item['address'] = address
item['cars'] = cars
yield item
关于python - xpath 有一个空值,这会弄乱列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144983/