我正在从一页中提取数据。当然,我必须更深入,但我仍然停留在第一页。这是我的代码:
from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import HtmlXPathSelector
from street.items import HstreetItem
class MySpider(CrawlSpider):
name = "go-h"
allowed_domains = ["http://somedomain.com"]
start_urls = ["http://somedomain.com"]
def parse(self,response):
#response = response.replace(body=response.body.replace('\n', '')) # doesn't work
hxs = HtmlXPathSelector(response)
details = hxs.select('//tr')
items = []
#n = 0
for detail in details:
item = HondastreetItem()
item['url'] = "".join(detail.select('td[@class="Model_LineModel_odd"]/a/@href | td[@class="Model_LineModel_even"]/a/@href').extract()).strip()
item['model'] = "".join(detail.select('td[@class="Model_LineModel_odd"]/a/text() | td[@class="Model_LineModel_even"]/a/text()').extract())
item['year'] = "".join(detail.select('td[@class="Model_LineYear_odd"]/text() | td[@class="Model_LineYear_even"]/text()').extract())
items.append(item)
return items
代码工作正常,它通过我的管道将数据提取到 CSV 文件中,就像它应该的那样:
cell 1 | cell2 | cell3
url | model | year
.
.
.
问题是我的 csv 文件中有很多空行。在我的 CSV 文件的开头 17 行,然后是填充行之间的空行。我认为爬网表前面的一些表和爬网表内我不需要的一些行(如类别名称)导致了这种情况。 我在过去的 24 小时里陷入了困境:(我一直在尝试通过类似问题找到的所有解决方案,但没有任何效果对我有用。
感谢您的帮助!
我对 Python 很陌生,来到这里试图理解 scrapy。
据我了解,您必须附加空行。因此,您可能会尝试在追加语句之前检查“item”是否不为空,例如,
if not (item['url'] == "" and item['model'] == "" and item['year'] == ""):
items.append(item)
如果我误解了问题,请忽略。