我想知道为什么在刮the的外壳中我确实能得到我的结果,但是当我尝试在脚本中使用它的时候。它失败并显示空字段。你会怎么称呼以及如何修复?
外壳:
>>> response.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(9) > span:nth-child(1)::text").extract_first()
u'GU17 9AB'
我的代码段:
import scrapy
import re
from scrapy.linkextractors import LinkExtractor
class QuotesSpider(scrapy.Spider):
name = 'CYRecursive'
start_urls = [
'https://www.companiesintheuk.co.uk/Company/Find?q=a']
def parse(self, response):
for company_url in response.xpath('//div[@class="search_result_title"]/a/@href').extract():
yield scrapy.Request(
url=response.urljoin(company_url),
callback=self.parse_details,
)
def parse_details(self, response):
# Looping throught the searchResult block and yielding it
for i in response.css('div.col-md-6'):
if not i.css('#content2 > strong:nth-child(2) > strong:nth-child(1)'):
continue
yield {
'company_name': i.css('#content2 > strong:nth-child(2) > strong:nth-child(1) > div:nth-child(1)::text').get(),
'address': i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(1)::text").extract_first(),
'location': i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > span:nth-child(3)::text").extract_first(),
'postal_code': i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(9) > span:nth-child(1)::text").extract_first(),
}
给我带来麻烦的部分是:
'postal_code': i.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(9) > span:nth-child(1)::text").extract_first(),
谢谢!
答案 0 :(得分:1)
不确定这是否是您想要的东西。请尝试以下操作:
def parse_details(self, response):
for i in response.css('#content2'):
yield {
'company_name': i.css('[itemprop="name"]::text').get(),
'address': i.css('[itemprop="streetAddress"]::text').extract_first(),
'location': i.css("[itemprop='addressLocality']::text").extract_first(),
'postal_code': i.css("[itemprop='postalCode']::text").extract_first(),
}