scrapy crawl letter运行下面的代码,但是总是能运行但是不能下载文件。
import scrapy,json,requests,os
import pandas as pd
from numpy import random
from datetime import datetime
from report_downloader.items import ReportDownloaderItem
class LetterSpider(scrapy.Spider):
name = 'letter'
allowed_domains = ['eastmoney.com']
def start_requests(self):
# 读取股票列表
index_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'股票代码.xlsx')
df = pd.read_excel(index_path,dtype={'代码':str})
code_list = df['代码']
for code in code_list:
# 设置api网址
baseurl = 'https://np-anotice-stock.eastmoney.com/api/security/ann?'
# 获取当前时间戳
ts = int(datetime.now().timestamp()*1000)
cb = 'jQuery11230{}{}_{}'.format(random.randint(100000000,499999999),random.randint(10000000,99999999),ts)
# 设置请求表单
formdata = {
'cb':cb,
'sr':'-1',
'page_size':'50',
'page_index':1,
'ann_type':'A',
'client_source':'web',
'stock_list':code,
'f_node':'0',
's_node':'0',
}
# 发起一次请求,获取总页数
url = '{}{}'.format(baseurl,'&'.join(['{}={}'.format(x[0],x[1]) for x in formdata.items()]))
r = requests.get(url,data=formdata)
r = json.loads(r.text.replace('{}('.format(cb),'').replace(')',''))
finalpage = r['data']['total_hits']//50
# 只遍历最后三页,每页查看50条文件列表
for page in range(finalpage-2,finalpage+2):
# 重设时间戳
ts = int(datetime.now().timestamp()*1000)
cb = 'jQuery11230{}{}_{}'.format(random.randint(100000000,499999999),random.randint(10000000,99999999),ts)
formdata = {
'cb':cb,
'sr':'-1',
'page_size':'50',
'page_index':page,
'ann_type':'A',
'client_source':'web',
'stock_list': code,
'f_node':'0',
's_node':'0',
}
# 发起请求
url = '{}{}'.format(baseurl,'&'.join(['{}={}'.format(x[0],x[1]) for x in formdata.items()]))
yield scrapy.Request(url,meta={'cb':cb},callback=self.get_list,dont_filter=True)
def get_list(self, response):
li = json.loads(response.text.replace('{}('.format(response.meta['cb']),'').replace(')',''))['data']['list']
for one in li:
name = one['title'].replace('\\',' ').replace('/',' ')
# 回复意见
# if ('发行人' in one['title']) and ('回复意见' in one['title']) and ('落实' not in one['title']):
# title = '{}_{}_{}.pdf'.format(one['codes'][0]['stock_code'],one['codes'][0]['short_name'],name)
# durl = 'https://pdf.dfcfw.com/pdf/H2_{}_1.pdf'.format(one['art_code'])
# item = ReportDownloaderItem(title=title,durl=durl)
# yield item
# 招股说明书
if ('招股说明书' in one['title']) and ('首次公开' in one['title'])and ('摘要' not in one['title']) and ('上会' not in one['title'])and ('申报' not in one['title'])and ('注册' not in one['title']):
title = '{}_{}_{}.pdf'.format(one['codes'][0]['stock_code'],one['codes'][0]['short_name'],name)
durl = 'https://pdf.dfcfw.com/pdf/H2_{}_1.pdf'.format(one['art_code'])
item = ReportDownloaderItem(title=title,durl=durl)
yield item
这就是运行的结果,各位给看看
PS F:\IPO_crawler-main\report_downloader> scrapy crawl letter
2024-07-14 19:51:35 [scrapy.utils.log] INFO: Scrapy 2.11.2 started (bot: report_downloader)
2024-07-14 19:51:36 [scrapy.utils.log] INFO: Versions: lxml 5.2.2.0, libxml2 2.11.7, cssselect 1.2.0, parsel 1.9.1, w3lib 2.2.1, Twisted 24.3.0, Python 3.12.3 | packaged by conda-forge | (main,
Apr 15 2024, 18:20:11) [MSC v.1938 64 bit (AMD64)], pyOpenSSL 24.1.0 (OpenSSL 3.2.2 4 Jun 2024),
cryptography 42.0.8, Platform Windows-10-10.0.19045-SP0
2024-07-14 19:51:36 [scrapy.addons] INFO: Enabled addons:
[]
2024-07-14 19:51:36 [py.warnings] WARNING: D:\anaconda\envs\fraud_env\Lib\site-packages\scrapy\utils\request.py:254: ScrapyDeprecationWarning: '2.6' is a deprecated value for the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting.
It is also the default value. In other words, it is normal to get this warning if you have not defined a value for the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting. This is so for backward compatibility reasons, but it will change in a future version of Scrapy.
See the documentation of the 'REQUEST_FINGERPRINTER_IMPLEMENTATION' setting for information on how to handle this deprecation.
return cls(crawler)
2024-07-14 19:51:36 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2024-07-14 19:51:36 [scrapy.extensions.telnet] INFO: Telnet Password: 77d3334bb7b13664
2024-07-14 19:51:36 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.logstats.LogStats']
2024-07-14 19:51:36 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'report_downloader',
'NEWSPIDER_MODULE': 'report_downloader.spiders',
'SPIDER_MODULES': ['report_downloader.spiders']}
2024-07-14 19:51:36 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.offsite.OffsiteMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2024-07-14 19:51:36 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2024-07-14 19:51:36 [py.warnings] WARNING: D:\anaconda\envs\fraud_env\Lib\site-packages\scrapy\pipelines\media.py:148: ScrapyDeprecationWarning: file_path(self, request, response=None, info=None) is deprecated, please use file_path(self, request, response=None, info=None, *, item=None)
self._check_signature(func)
2024-07-14 19:51:36 [scrapy.middleware] INFO: Enabled item pipelines:
['report_downloader.pipelines.ReportDownloaderPipeline']
2024-07-14 19:51:36 [scrapy.core.engine] INFO: Spider opened
2024-07-14 19:51:36 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped
0 items (at 0 items/min)
2024-07-14 19:51:36 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2024-07-14 19:51:37 [urllib3.connectionpool] DEBUG: Starting new HTTPS connection (1): np-anotice-stock.eastmoney.com:443
2024-07-14 19:51:37 [urllib3.connectionpool] DEBUG: https://np-anotice-stock.eastmoney.com:443 "GET /api/security/ann?cb=jQuery1123048249952422348865_1720957897289&sr=-1&page_size=50&page_index=1&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0 HTTP/1.1" 200 34582
2024-07-14 19:51:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://np-anotice-stock.eastmoney.com/api/security/ann?cb=jQuery1123021207829864337257_1720957897621&sr=-1&page_size=50&page_index=8&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0> (referer: None)
2024-07-14 19:51:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://np-anotice-stock.eastmoney.com/api/security/ann?cb=jQuery1123038682287218392616_1720957897614&sr=-1&page_size=50&page_index=7&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0> (referer: None)
2024-07-14 19:51:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://np-anotice-stock.eastmoney.com/api/security/ann?cb=jQuery1123034284541950785597_1720957897625&sr=-1&page_size=50&page_index=10&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0> (referer: None)
2024-07-14 19:51:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://np-anotice-stock.eastmoney.com/api/security/ann?cb=jQuery1123040443715152602585_1720957897623&sr=-1&page_size=50&page_index=9&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0> (referer: None)
2024-07-14 19:51:38 [scrapy.downloadermiddlewares.offsite] DEBUG: Filtered offsite request to 'pdf.dfcfw.com': <GET https://pdf.dfcfw.com/pdf/H2_AN202203061551011071_1.pdf>
2024-07-14 19:51:38 [scrapy.pipelines.media] ERROR: [Failure instance: Traceback: <class 'scrapy.pipelines.files.FileException'>:
D:\anaconda\envs\fraud_env\Lib\site-packages\twisted\internet\defer.py:536:addCallbacks
D:\anaconda\envs\fraud_env\Lib\site-packages\twisted\internet\defer.py:1078:_runCallbacks
D:\anaconda\envs\fraud_env\Lib\site-packages\scrapy\pipelines\media.py:197:_check_media_to_download
D:\anaconda\envs\fraud_env\Lib\site-packages\twisted\internet\defer.py:536:addCallbacks
--- <exception caught here> ---
D:\anaconda\envs\fraud_env\Lib\site-packages\twisted\internet\defer.py:1078:_runCallbacks
D:\anaconda\envs\fraud_env\Lib\site-packages\scrapy\pipelines\files.py:459:media_failed
]
NoneType: None
2024-07-14 19:51:38 [scrapy.core.scraper] DEBUG: Scraped from <200 https://np-anotice-stock.eastmoney.com/api/security/ann?cb=jQuery1123040443715152602585_1720957897623&sr=-1&page_size=50&page_index=9&ann_type=A&client_source=web&stock_list=001308&f_node=0&s_node=0>
{'durl': 'https://pdf.dfcfw.com/pdf/H2_AN202203061551011071_1.pdf',
'title': '001308_康冠科技_康冠科技:首次公开发行股票招股说明书.pdf'}
2024-07-14 19:51:38 [scrapy.core.engine] INFO: Closing spider (finished)
2024-07-14 19:51:38 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/exception_count': 1,
'downloader/exception_type_count/scrapy.exceptions.IgnoreRequest': 1,
'downloader/request_bytes': 1541,
'downloader/request_count': 4,
'downloader/request_method_count/GET': 4,
'downloader/response_bytes': 108593,
'downloader/response_count': 4,
'downloader/response_status_count/200': 4,
'elapsed_time_seconds': 1.250309,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2024, 7, 14, 11, 51, 38, 199251, tzinfo=datetime.timezone.utc), 'item_scraped_count': 1,
'log_count/DEBUG': 9,
'log_count/ERROR': 1,
'log_count/INFO': 10,
'log_count/WARNING': 2,
'offsite/domains': 1,
'offsite/filtered': 1,
'response_received_count': 4,
'scheduler/dequeued': 4,
'scheduler/dequeued/memory': 4,
'scheduler/enqueued': 4,
'scheduler/enqueued/memory': 4,
'start_time': datetime.datetime(2024, 7, 14, 11, 51, 36, 948942, tzinfo=datetime.timezone.utc)}
2024-07-14 19:51:38 [scrapy.core.engine] INFO: Spider closed (finished)