【发布时间】:2019-10-01 11:45:40
【问题描述】:
我正在尝试从公司注册中刮取一些数据,到目前为止,它可以刮取每个搜索结果,但是当我尝试将其导出时。它在每个搜索结果之后显示一个空对象,就好像它刮了同一个页面两次一样?
这是日志的 sn-p。
2019-05-14 08:19:21 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.companiesintheuk.co.uk/ltd/a-c-1> (referer: https://www.companiesintheuk.co.uk/Company/Find?q=a)
2019-05-14 08:19:21 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.companiesintheuk.co.uk/ltd/a-c-1>
{'location': u'BEANCROFT ROAD', 'postal_code': None, 'company_name': u'A C PLC', 'address': u'BEANCROFT FARM'}
2019-05-14 08:19:21 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.companiesintheuk.co.uk/ltd/a-c-1>
{'location': None, 'postal_code': None, 'company_name': None, 'address': None}
最后是我的代码
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'):
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(5) > span:nth-child(1)::text").extract_first(),
}
提前谢谢你!
【问题讨论】:
-
这些页面上的 HTML 完全无效 - 它有许多重复的 ID - 所以您可能永远无法从中获得正确的结果。在任何情况下,您都应该考虑使用实际的Companies House API,而不是试图抓取这个狡猾的网站。
-
非常感谢,我会研究那个 API!
标签: python json web-scraping scrapy