我正在用下面的代码从网页上刮下姓名、地址和汽车数量。你知道吗
然而,汽车数量常常有一个空值。在下面的示例中,假设第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
试试这个结果。您可以在scrapy项目中使用
xpaths
,如下所示:部分输出:
你的选择器循环有点混乱。你知道吗
在这里,您可以循环浏览未排序的列表,其中每个年龄段只有一个:
您要做的是遍历所有列表项:
如果以这种方式循环,则可以获得每个列表项的名称、地址:
相关问题 更多 >
编程相关推荐