Commit 834e89d6 by 郭峰

初始化

parents
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" autoUpload="Always" serverName="souhcars_linux" remoteFilesAllowedToDisappearOnAutoupload="false">
<serverData>
<paths name="souhcars_linux">
<serverdata>
<mappings>
<mapping deploy="/souhcars" local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
<option name="myAutoUpload" value="ALWAYS" />
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="22">
<item index="0" class="java.lang.String" itemvalue="zipp" />
<item index="1" class="java.lang.String" itemvalue="SQLAlchemy" />
<item index="2" class="java.lang.String" itemvalue="wcwidth" />
<item index="3" class="java.lang.String" itemvalue="sqlacodegen" />
<item index="4" class="java.lang.String" itemvalue="urllib3" />
<item index="5" class="java.lang.String" itemvalue="pycrypto" />
<item index="6" class="java.lang.String" itemvalue="locust" />
<item index="7" class="java.lang.String" itemvalue="jupyter-core" />
<item index="8" class="java.lang.String" itemvalue="pycairo" />
<item index="9" class="java.lang.String" itemvalue="jupyter-client" />
<item index="10" class="java.lang.String" itemvalue="MarkupSafe" />
<item index="11" class="java.lang.String" itemvalue="pygobject" />
<item index="12" class="java.lang.String" itemvalue="chardet" />
<item index="13" class="java.lang.String" itemvalue="Django" />
<item index="14" class="java.lang.String" itemvalue="PyYAML" />
<item index="15" class="java.lang.String" itemvalue="certifi" />
<item index="16" class="java.lang.String" itemvalue="pyDes" />
<item index="17" class="java.lang.String" itemvalue="PyMySQL" />
<item index="18" class="java.lang.String" itemvalue="pytz" />
<item index="19" class="java.lang.String" itemvalue="requests" />
<item index="20" class="java.lang.String" itemvalue="djangorestframework" />
<item index="21" class="java.lang.String" itemvalue="idna" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (souhcars)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/souhcars.iml" filepath="$PROJECT_DIR$/.idea/souhcars.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.7 (souhcars)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SshConfigs">
<configs>
<sshConfig authType="PASSWORD" host="47.100.68.39" id="8dd09262-fa1d-4e37-872c-8714176cc970" port="22" nameFormat="DESCRIPTIVE" username="root" useOpenSSHConfig="true" />
</configs>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="WebServers">
<option name="servers">
<webServer id="b8ac0761-a4fd-456b-a030-372b2f3716e8" name="souhcars_linux">
<fileTransfer rootFolder="/usr/local/python/" accessType="SFTP" host="47.100.68.39" port="22" sshConfigId="8dd09262-fa1d-4e37-872c-8714176cc970" sshConfig="root@47.100.68.39:22 password">
<advancedOptions>
<advancedOptions controlEncoding="UTF-8" dataProtectionLevel="Private" keepAliveTimeout="0" passiveMode="true" shareSSLContext="true" />
</advancedOptions>
</fileTransfer>
</webServer>
</option>
</component>
</project>
\ No newline at end of file
from scrapy import cmdline
cmdline.execute('scrapy crawl souh_cars'.split())
\ No newline at end of file
# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings]
default = souhcars.settings
[deploy]
#url = http://localhost:6800/
project = souhcars
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class BrandItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
brand_id = scrapy.Field() # 品牌
brand_name = scrapy.Field() # 品牌名称
class SeriesItem(scrapy.Item):
brand_id = scrapy.Field()
maker_name = scrapy.Field()
maker_id = scrapy.Field()
series_id = scrapy.Field()
series_name = scrapy.Field()
class StyleItem(scrapy.Item):
series_id = scrapy.Field()
style_id = scrapy.Field()
style_name = scrapy.Field()
conf = scrapy.Field()
# 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
class SouhcarsSpiderMiddleware:
# 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 SouhcarsDownloaderMiddleware:
# 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)
# 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
import pymysql as pymysql
import souhcars.items
class SouhcarsPipeline:
def __init__(self):
self.host = "47.100.68.39"
self.port = 3310
self.database = "db_spider"
self.user = "root"
self.password = "dip-test"
self.con = pymysql.connect(host=self.host, port=self.port, database=self.database, user=self.user,
password=self.password)
self.cu = self.con.cursor()
print("实例化了数据库")
def process_item(self, item, spider):
if isinstance(item, souhcars.items.BrandItem):
sql_q = 'select id from t_brand_souh where brand_id = "{}"'.format(item['brand_id'])
sql = 'insert into t_brand_souh (brand_id, brand_name) values ("{}","{}")' \
.format(item['brand_id'], item['brand_name'])
self.con.ping(reconnect=True)
self.cu.execute(sql_q)
if str(self.cu.fetchone()) != 'None':
return
self.cu.execute(sql)
self.con.commit()
elif isinstance(item, souhcars.items.SeriesItem):
sql_q = 'select id from t_series_souh where series_id = "{}"'.format(item['series_id'])
sql = 'insert into t_series_souh (brand_id, maker_id, maker_name, series_id, series_name)' \
' values ("{}","{}","{}","{}","{}")'.format(item['brand_id'], item['maker_id'], item['maker_name'],
item['series_id'], item['series_name'])
self.con.ping(reconnect=True)
self.cu.execute(sql_q)
if str(self.cu.fetchone()) != 'None':
return
self.cu.execute(sql)
self.con.commit()
elif isinstance(item, souhcars.items.StyleItem):
sql_q = 'select id from t_style_souh where style_id = "{}"'.format(item['style_id'])
sql = 'insert into t_style_souh (series_id, style_id, style_name, conf)' \
' values ("{}","{}","{}","{}")'.format(item['series_id'], item['style_id'], item['style_name'],
item['conf'])
self.con.ping(reconnect=True)
self.cu.execute(sql_q)
if str(self.cu.fetchone()) != 'None':
return
self.cu.execute(sql)
self.con.commit()
def __del__(self):
self.cu.close()
self.con.close()
# Scrapy settings for souhcars 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 = 'souhcars'
SPIDER_MODULES = ['souhcars.spiders']
NEWSPIDER_MODULE = 'souhcars.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'souhcars (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
'Chrome/99.0.4844.82 Safari/537.36'
# 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 = 1
# 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
LOG_LEVEL = "INFO"
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/99.0.4844.82 Safari/537.36'
}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
# 'souhcars.middlewares.SouhcarsSpiderMiddleware': 543,
# }
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
# 'souhcars.middlewares.SouhcarsDownloaderMiddleware': 543,
# }
# 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 = {
'souhcars.pipelines.SouhcarsPipeline': 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'
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import json
import re
from json import JSONDecodeError
import scrapy
from souhcars.items import BrandItem, SeriesItem, StyleItem
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError, TCPTimedOutError
class SouhCarsSpider(scrapy.Spider):
name = 'souh_cars'
allowed_domains = ['auto.sohu.com']
start_urls = ['http://db.auto.sohu.com/home/']
def parse(self, response, **kwargs):
# flag = 0
all_brand_li = response.xpath('//*[@id="treeNav"]/ul/li[@class="close_child"]')
for i in all_brand_li:
# 保存品牌
brand = BrandItem()
brand['brand_name'] = i.xpath('h4/a/text()').extract()[1]
brand['brand_id'] = i.xpath('h4/a').attrib.get('id')
yield brand
# 保存车系
all_maker_li = i.xpath("ul")
series = SeriesItem()
series['brand_id'] = i.xpath('h4/a').attrib.get('id')
for j in all_maker_li:
series['maker_id'] = j.xpath('li[@class="con_tit"]/a').attrib.get('id')
series['maker_name'] = j.xpath('li[@class="con_tit"]/a/text()').extract()[1].strip()
all_series_li = j.xpath('li/a[@class="model-a"]')
for k in all_series_li:
try:
series['series_name'] = k.xpath('text()').extract()[1].strip()
except IndexError as e:
print(e)
return
series['series_id'] = k.attrib.get('id')
yield series
# 车的参数配置信息地址
style_url ='http:'+ k.attrib.get('href') +'/trim.html'
yield scrapy.Request(url=style_url, callback=self.parse_years, errback=self.parse_err)
def parse_years(self, response, **kwargs):
all_year = response.xpath('//*[@id="yearp"]/a[@target="_blank"]/text()')
# 如果只有一个年款,那么上面方式查不到年款,如果查不到,就是用下面方式再查一次
if len(all_year) == 0:
# print(response.url)
all_year = response.xpath('//*[@id="yearp"]/a/text()')
for i in all_year:
style_url2 = response.url.replace('trim.html', 'trim_year{}.html'.format(i.root[0:4]))
yield scrapy.Request(url=style_url2, callback=self.parse_style, errback=self.parse_err)
def parse_style(self, response, **kwargs):
regex = re.compile(r"var trimParam = ([\s\S]*?)}];")
try:
all_style = json.loads(response.selector.re(regex)[0] + "}]")
except JSONDecodeError as e:
print(e)
print(response.selector.re(regex)[0])
print(response.url)
return
for i in all_style:
style = StyleItem()
style['style_id'] = i.get('SIP_T_ID')
style['style_name'] = i.get('subbrandName') + ' ' + i.get('modelName') + ' ' + str(i.get('SIP_T_YEAR'))\
+ '款 ' + i.get('SIP_T_NAME')
style['series_id'] = i.get('SIP_T_MODELID')
style['conf'] = str(i).replace("\"", "\\\"")
yield style
def parse_err(self, failure):
if failure.check(HttpError):
response = failure.value.response
print('HttpError on {0}'.format(response.url))
elif failure.check(DNSLookupError):
request = failure.request
print('DNSLookupError on {0}'.format(request.url))
elif failure.check(TimeoutError, TCPTimedOutError):
request = failure.request
print('TimeoutError on {0}'.format(request.url))
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment