I’m trying to scrape from a commerce website using Scrapy. For the price tag, I want to remove the “$”, but my current code does not work.
JavaScript
x
9
1
def parse(self, response):
2
for sel in response.xpath('//section[@class="items-box"]'):
3
item = ShopItem()
4
item['name'] = sel.xpath('a/div/h3/text()').extract()
5
item['price'] = sel.xpath('a/div/div/div[1]/text()').extract().replace("$", "")
6
yield item
7
8
AttributeError: 'list' object has no attribute 'replace'
9
What is the appropriate method to remove characters when using Scrapy?
Advertisement
Answer
extract()
would return you a list, you can use extract_first()
to get a single value:
JavaScript
1
2
1
item['price'] = sel.xpath('a/div/div/div[1]/text()').extract_first().replace("$", "")
2
Or, you can use the .re()
method, something like:
JavaScript
1
2
1
item['price'] = sel.xpath('a/div/div/div[1]/text()').re(r"$(.*?)")
2