Python 为什么我在shell中得到结果而不是导出?
我想知道为什么我在scrapy shell中得到了我的结果,然而当我尝试在脚本中实现它时。它失败并显示空字段。那你叫什么?它是如何修复的 我的输出的屏幕截图: 壳牌公司:Python 为什么我在shell中得到结果而不是导出?,python,web-scraping,scrapy,Python,Web Scraping,Scrapy,我想知道为什么我在scrapy shell中得到了我的结果,然而当我尝试在脚本中实现它时。它失败并显示空字段。那你叫什么?它是如何修复的 我的输出的屏幕截图: 壳牌公司: >>> response.css("#content2 > strong:nth-child(2) > address:nth-child(2) > div:nth-child(1) > a:nth-child(9) > span:nth-child(1)::text").ex
>>> 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(),
谢谢大家! 不确定这是否是您想要的。请尝试以下操作:
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(),
}
编辑:这一行可能会给出空值:“邮政编码”:i.css(“#content2>strong:nth child(2)>address:nth child(2)>div:nth child(1)>a:nth child(9)>span:nth child(1)::text”)。如果需要澄清问题,请先提取,点击链接。你能不能试着把代码片段变成一个--其他人可以运行的最短的自包含代码,以查看问题本身,而不需要进行更改或添加?我刚刚回答了这个问题谢谢,还发布了完整的代码!如果给出的代码实际上没有调用生成错误的函数,并生成显示错误是否发生的输出,那就不是一个MCVE。这正是我想要的!我从来都不知道“itemprop”属性!它有一个特定的名字吗?我可以在剪贴指南中找到它。这都是关于选择器的事情。它们被称为属性选择器。谢谢!我一定会更深入地研究它!