middlewares.py
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter from fake_useragent import UserAgent class TianyanchaSpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, or item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Request or item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info("Spider opened: %s" % spider.name) class TianyanchaDownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info("Spider opened: %s" % spider.name) class RandomUserAgent: def __init__(self) -> None: self.cookies_file = 'cookies.txt' self.cookies = {} def process_request(self, request, spider): self.read_cookies() ua = UserAgent() request.headers['User-Agent'] = ua.random request.cookies = self.cookies print(' ---hhhhhhhhhhhh', request.headers) def read_cookies(self): self.cookies = {} with open(self.cookies_file, 'r') as f: lines = f.read().split(';') for line in lines: name, value = self.split_cookie_item(line.strip()) self.cookies[name] = value def split_cookie_item(self, item): index = item.find('=') key = item[:index] value = item[index + 1:] return key, value if __name__ == '__main__': a = RandomUserAgent() a.read_cookies()
pipelines.py
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter class TianyanchaPipeline: def __init__(self) -> None: self.file = open('tianyancha.txt', 'w', encoding='utf-8') def __del__(self): self.file.close() def process_item(self, item, spider): item = dict(item) self.file.write(str(item) + ',\n') self.file.flush() return item
settings.py
# Scrapy settings for tianyancha project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = "tianyancha" SPIDER_MODULES = ["tianyancha.spiders"] NEWSPIDER_MODULE = "tianyancha.spiders" # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = "tianyancha (+http://www.yourdomain.com)" # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 15 RAMDOMIZE_DOWNLOAD_DELAY = True # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", # "Accept-Language": "en", #} # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # "tianyancha.middlewares.TianyanchaSpiderMiddleware": 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { "tianyancha.middlewares.TianyanchaDownloaderMiddleware": 543, "tianyancha.middlewares.RandomUserAgent": 542, } # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # "scrapy.extensions.telnet.TelnetConsole": None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { "tianyancha.pipelines.TianyanchaPipeline": 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = "httpcache" #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage" # Set settings whose default value is deprecated to a future-proof value REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7" TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor" FEED_EXPORT_ENCODING = "utf-8"
items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class TianyanchaItem(scrapy.Item): # 公司名称 name = scrapy.Field() # 法人 legal_person = scrapy.Field() # 注册资本 registered_capital = scrapy.Field() # 注册时间 registered_time = scrapy.Field() # 经营状态 business_status = scrapy.Field() # 统一信用代码 credit_code = scrapy.Field() # 地址 address = scrapy.Field() # 邮箱 email = scrapy.Field() # url url = scrapy.Field() # 员工人数 staff_num = scrapy.Field()
tianyancha_cs.py
import scrapy from tianyancha.items import TianyanchaItem from scrapy import Request class TianyanchaCsSpider(scrapy.Spider): name = "tianyancha_cs" allowed_domains = ["tianyancha.com"] def start_requests(self): url = "https://www.tianyancha.com/search?key=&base=hun&city=zhangsha&cacheCode=00430100V2020&sessionNo=1707115565.34684048&moneyStart=1000&moneyEnd=null&pageNum={}" for i in range(1, 10): yield Request(url.format(i), callback=self.parse) def parse(self, response): # print(response.request.headers) # print(response.body) # with open('tianyancha.html', 'w', encoding='utf-8') as f: # f.write(response.body.decode('utf-8')) node_list = response.xpath('//div[@class="index_header__x2QZ3"]/div[@class="index_name__qEdWi"]/a/@href') print(len(node_list)) for node in node_list: item = TianyanchaItem() item['url'] = node.extract() if item['url']: yield scrapy.Request(url=item['url'], meta={'item': item}, callback=self.parse_detail) def parse_detail(self, response): item = response.meta['item'] # with open('tianyancha_detail.html', 'w', encoding='utf-8') as f: # f.write(response.body.decode('utf-8')) item['name'] = response.xpath('//h1[@class="index_company-name__LqKlo"]/text()').extract_first() item['legal_person'] = response.xpath('//a[@class="index_link-click__NmHxP"]/text()').extract_first() item['registered_capital'] = response.xpath('//*[@id="page-root"]/div[3]/div/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[3]/span[2]/text()').extract_first() item['registered_time'] = response.xpath('//*[@id="page-root"]/div[3]/div/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[4]/span[2]/text()').extract_first() item['business_status'] = '' item['credit_code'] = response.xpath('//*[@id="page-root"]/div[3]/div/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div/span/text()').extract_first() item['address'] = response.xpath('//span[@class="index_copy-text__ri7W6 index_detail-address-moretext__9R_Z1"]/text()').extract_first() item['email'] = response.xpath('//a[@class="index_detail-email__B_1Tq"]/text()').extract_first() item['staff_num'] = response.xpath('//*[@id="page-root"]/div[3]/div/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[3]/div[3]/span[2]/span/text()').extract_first() print(item) yield item