【发布时间】:2017-09-18 06:16:24
【问题描述】:
我最近开始使用 Scrapy,正在尝试清理一些我已经抓取并希望导出为 CSV 的数据,即以下三个示例:
- 示例 1 – 删除某些文本
- 示例 2 – 删除/替换不需要的字符
- 示例 3 - 拆分逗号分隔文本
示例 1 数据如下所示:
我想要的文字,我不想要的文字
使用以下代码:
'Scraped 1': response.xpath('//div/div/div/h1/span/text()').extract()
示例 2 的数据如下所示:
- 但我想将其更改为 £
使用以下代码:
' Scraped 2': response.xpath('//html/body/div/div/section/div/form/div/div/em/text()').extract()
示例 3 数据如下所示:
Item 1,Item 2,Item 3,Item 4,Item 4,Item5 – 最终我想拆分 将其放入 CSV 文件中的单独列中
使用以下代码:
' Scraped 3': response.xpath('//div/div/div/ul/li/p/text()').extract()
我尝试过使用str.replace(),但似乎无法让它发挥作用,例如:
'Scraped 1': response.xpath('//div/div/div/h1/span/text()').extract((str.replace(",Text I don't want",""))
我正在研究这个问题,但如果有人能指出我正确的方向,我将不胜感激!
代码如下:
import scrapy
from scrapy.loader import ItemLoader
from tutorial.items import Product
class QuotesSpider(scrapy.Spider):
name = "quotes_product"
start_urls = [
'http://www.unitestudents.com/',
]
# Step 1
def parse(self, response):
for city in response.xpath('//select[@id="frm_homeSelect_city"]/option[not(contains(text(),"Select your city"))]/text()').extract(): # Select all cities listed in the select (exclude the "Select your city" option)
yield scrapy.Request(response.urljoin("/"+city), callback=self.parse_citypage)
# Step 2
def parse_citypage(self, response):
for url in response.xpath('//div[@class="property-header"]/h3/span/a/@href').extract(): #Select for each property the url
yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage)
# Step 3
def parse_unitpage(self, response):
for final in response.xpath('//div/div/div[@class="content__btn"]/a/@href').extract(): #Select final page for data scrape
yield scrapy.Request(response.urljoin(final), callback=self.parse_final)
#Step 4
def parse_final(self, response):
unitTypes = response.xpath('//html/body/div').extract()
for unitType in unitTypes: # There can be multiple unit types so we yield an item for each unit type we can find.
l = ItemLoader(item=Product(), response=response)
l.add_xpath('area_name', '//div/ul/li/a/span/text()')
l.add_xpath('type', '//div/div/div/h1/span/text()')
l.add_xpath('period', '/html/body/div/div/section/div/form/h4/span/text()')
l.add_xpath('duration_weekly', '//html/body/div/div/section/div/form/div/div/em/text()')
l.add_xpath('guide_total', '//html/body/div/div/section/div/form/div/div/p/text()')
l.add_xpath('amenities','//div/div/div/ul/li/p/text()')
return l.load_item()
但是,我得到以下信息?
value = self.item.fields[field_name].get(key, default)
KeyError: 'type'
【问题讨论】:
标签: python web-scraping scrapy data-cleaning