Python爬虫之Scrapy环境搭建案例教程
python爬虫之scrapy环境搭建
如何搭建scrapy环境
首先要安装python环境,python环境搭建见:https://blog.csdn.net/alice_tl/article/details/76793590
接下来安装scrapy
1、安装scrapy,在终端使用pip install scrapy(注意最好是国外的环境)
进度提示如下:
alicedemacbook-pro:~ alice$ pip install scrapy collecting scrapy using cached https://files.pythonhosted.org/packages/5d/12/a6197eaf97385e96fd8ec56627749a6229a9b3178ad73866a0b1fb377379/scrapy-1.5.1-py2.py3-none-any.whl collecting w3lib>=1.17.0 (from scrapy) using cached https://files.pythonhosted.org/packages/37/94/40c93ad0cadac0f8cb729e1668823c71532fd4a7361b141aec535acb68e3/w3lib-1.19.0-py2.py3-none-any.whl collecting six>=1.5.2 (from scrapy) xxxxxxxxxxxxxxxxxxxxx file "/system/library/frameworks/python.framework/versions/2.7/extras/lib/python/setuptools/dist.py", line 380, in fetch_build_egg return cmd.easy_install(req) file "/system/library/frameworks/python.framework/versions/2.7/extras/lib/python/setuptools/command/easy_install.py", line 632, in easy_install raise distutilserror(msg) distutils.errors.distutilserror: could not find suitable distribution for requirement.parse('incremental>=16.10.1') ---------------------------------------- command "python setup.py egg_info" failed with error code 1 in /private/var/folders/v1/9x8s5v8x74v86vnpqyttqy280000gn/t/pip-install-u_6vzf/twisted/
出现缺少twisted的错误提示:
command "python setup.py egg_info" failed with error code 1 in /private/var/folders/v1/9x8s5v8x74v86vnpqyttqy280000gn/t/pip-install-u_6vzf/twisted/
2、安装twiseted,终端里输入:sudo pip install twisted==13.1.0
alicedemacbook-pro:~ alice$ pip install twisted==13.1.0 collecting twisted==13.1.0 downloading https://files.pythonhosted.org/packages/10/38/0d1988d53f140ec99d37ac28c04f341060c2f2d00b0a901bf199ca6ad984/twisted-13.1.0.tar.bz2 (2.7mb) 100% |████████████████████████████████| 2.7mb 398kb/s requirement already satisfied: zope.interface>=3.6.0 in /system/library/frameworks/python.framework/versions/2.7/extras/lib/python (from twisted==13.1.0) (4.1.1) requirement already satisfied: setuptools in /system/library/frameworks/python.framework/versions/2.7/extras/lib/python (from zope.interface>=3.6.0->twisted==13.1.0) (18.5) installing collected packages: twisted running setup.py install for twisted ... error complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/v1/9x8s5v8x74v86vnpqyttqy280000gn/t/pip-install-injwz2/twisted/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/v1/9x8s5v8x74v86vnpqyttqy280000gn/t/pip-record-omuvwf/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.macosx-10.13-intel-2.7 creating build/lib.macosx-10.13-intel-2.7/twisted copying twisted/copyright.py -> build/lib.macosx-10.13-intel-2.7/twisted copying twisted/_version.py -> build/li
3、再次使用sudo pip install scrapy安装,发现仍然出现错误提示,这次是没有安装lxml的错误提示:
could not find a version that satisfies the requirement lxml (from scrapy) (from versions: )
no matching distribution found for lxml (from scrapy)
alicedemacbook-pro:~ alice$ sudo pip install scrapy the directory '/users/alice/library/caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. please check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. the directory '/users/alice/library/caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. collecting scrapy downloading https://files.pythonhosted.org/packages/5d/12/a6197eaf97385e96fd8ec56627749a6229a9b3178ad73866a0b1fb377379/scrapy-1.5.1-py2.py3-none-any.whl (249kb) 100% |████████████████████████████████| 256kb 210kb/s collecting w3lib>=1.17.0 (from scrapy) xxxxxxxxxxxx downloading https://files.pythonhosted.org/packages/90/50/4c315ce5d119f67189d1819629cae7908ca0b0a6c572980df5cc6942bc22/twisted-18.7.0.tar.bz2 (3.1mb) 100% |████████████████████████████████| 3.1mb 59kb/s collecting lxml (from scrapy) could not find a version that satisfies the requirement lxml (from scrapy) (from versions: ) no matching distribution found for lxml (from scrapy)
4、安装lxml,使用:sudo pip install lxml
alicedemacbook-pro:~ alice$ sudo pip install lxml the directory '/users/alice/library/caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. please check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. the directory '/users/alice/library/caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. collecting lxml downloading https://files.pythonhosted.org/packages/a1/2c/6b324d1447640eb1dd240e366610f092da98270c057aeb78aa596cda4dab/lxml-4.2.4-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (8.7mb) 100% |████████████████████████████████| 8.7mb 187kb/s installing collected packages: lxml successfully installed lxml-4.2.4
5、再次安装scrapy,使用sudo pip install scrapy,安装成功
alicedemacbook-pro:~ alice$ sudo pip install scrapy the directory '/users/alice/library/caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. please check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. the directory '/users/alice/library/caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. if executing pip with sudo, you may want sudo's -h flag. collecting scrapy downloading https://files.pythonhosted.org/packages/5d/12/a6197eaf97385e96fd8ec56627749a6229a9b3178ad73866a0b1fb377379/scrapy-1.5.1-py2.py3-none-any.whl (249kb) 100% |████████████████████████████████| 256kb 11.5mb/s collecting w3lib>=1.17.0 (from scrapy) xxxxxxxxx requirement already satisfied: lxml in /library/python/2.7/site-packages (from scrapy) (4.2.4) collecting functools32; python_version < "3.0" (from parsel>=1.1->scrapy) retrying (retry(total=4, connect=none, read=none, redirect=none, status=none)) after connection broken by 'readtimeouterror("httpsconnectionpool(host='pypi.org', port=443): read timed out. (read timeout=15)",)': /simple/functools32/ downloading https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kb) 100% |████████████████████████████████| 61kb 66kb/s installing collected packages: w3lib, cssselect, functools32, parsel, queuelib, pydispatcher, attrs, pyasn1-modules, service-identity, zope.interface, constantly, incremental, automat, idna, hyperlink, pyhamcrest, twisted, scrapy running setup.py install for functools32 ... done running setup.py install for pydispatcher ... done found existing installation: zope.interface 4.1.1 uninstalling zope.interface-4.1.1: successfully uninstalled zope.interface-4.1.1 running setup.py install for zope.interface ... done running setup.py install for twisted ... done successfully installed automat-0.7.0 pydispatcher-2.0.5 pyhamcrest-1.9.0 scrapy-1.5.1 twisted-18.7.0 attrs-18.1.0 constantly-15.1.0 cssselect-1.0.3 functools32-3.2.3.post2 hyperlink-18.0.0 idna-2.7 incremental-17.5.0 parsel-1.5.0 pyasn1-modules-0.2.2 queuelib-1.5.0 service-identity-17.0.0 w3lib-1.19.0 zope.interface-4.5.0
6、检查scrapy是否安装成功,输入scrapy --version
出现scrapy的版本信息,比如:scrapy 1.5.1 - no active project即可。
alicedemacbook-pro:~ alice$ scrapy --version scrapy 1.5.1 - no active project usage: scrapy <command> [options] [args] available commands: bench run quick benchmark test fetch fetch a url using the scrapy downloader genspider generate new spider using pre-defined templates runspider run a self-contained spider (without creating a project) settings get settings values shell interactive scraping console startproject create new project version print scrapy version view open url in browser, as seen by scrapy [ more ] more commands available when run from project directory use "scrapy <command> -h" to see more info about a command
ps:如果中途没有能够正常访问org网和使用sudo管理员权限安装,则会出现类似的错误提示
exception:
traceback (most recent call last):
file "/library/python/2.7/site-packages/pip/_internal/basecommand.py", line 141, in main
status = self.run(options, args)
file "/library/python/2.7/site-packages/pip/_internal/commands/install.py", line 299, in run
resolver.resolve(requirement_set)
exception: traceback (most recent call last): file "/library/python/2.7/site-packages/pip/_internal/basecommand.py", line 141, in main status = self.run(options, args) file "/library/python/2.7/site-packages/pip/_internal/commands/install.py", line 299, in run resolver.resolve(requirement_set) file "/library/python/2.7/site-packages/pip/_internal/resolve.py", line 102, in resolve self._resolve_one(requirement_set, req) file "/library/python/2.7/site-packages/pip/_internal/resolve.py", line 256, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) file "/library/python/2.7/site-packages/pip/_internal/resolve.py", line 209, in _get_abstract_dist_for self.require_hashes file "/library/python/2.7/site-packages/pip/_internal/operations/prepare.py", line 283, in prepare_linked_requirement progress_bar=self.progress_bar file "/library/python/2.7/site-packages/pip/_internal/download.py", line 836, in unpack_url progress_bar=progress_bar file "/library/python/2.7/site-packages/pip/_internal/download.py", line 673, in unpack_http_url progress_bar) file "/library/python/2.7/site-packages/pip/_internal/download.py", line 897, in _download_http_url _download_url(resp, link, content_file, hashes, progress_bar) file "/library/python/2.7/site-packages/pip/_internal/download.py", line 617, in _download_url hashes.check_against_chunks(downloaded_chunks) file "/library/python/2.7/site-packages/pip/_internal/utils/hashes.py", line 48, in check_against_chunks for chunk in chunks: file "/library/python/2.7/site-packages/pip/_internal/download.py", line 585, in written_chunks for chunk in chunks: file "/library/python/2.7/site-packages/pip/_internal/download.py", line 574, in resp_read decode_content=false): file "/library/python/2.7/site-packages/pip/_vendor/urllib3/response.py", line 465, in stream data = self.read(amt=amt, decode_content=decode_content) file "/library/python/2.7/site-packages/pip/_vendor/urllib3/response.py", line 430, in read raise incompleteread(self._fp_bytes_read, self.length_remaining) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__ self.gen.throw(type, value, traceback) file "/library/python/2.7/site-packages/pip/_vendor/urllib3/response.py", line 345, in _error_catcher raise readtimeouterror(self._pool, none, 'read timed out.') readtimeouterror: httpsconnectionpool(host='files.pythonhosted.org', port=443): read timed out.
按照指南上搭建好了scrapy的环境。
scrapy爬虫运行常见报错及解决
按照第一个spider代码练习,保存在 tutorial/spiders 目录下的 dmoz_spider.py 文件中:
import scrapy class dmozspider(scrapy.spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/computers/programming/languages/python/books/", "http://www.dmoz.org/computers/programming/languages/python/resources/" ] def parse(self, response): filename = response.url.split("/")[-2] with open(filename, 'wb') as f: f.write(response.body)
terminal中运行:scrapy crawl dmoz,试图启动爬虫
报错提示一:
scrapy 1.6.0 - no active project
unknown command: crawl
alicedemacbook-pro:~ alice$ scrapy crawl dmoz scrapy 1.6.0 - no active project unknown command: crawl use "scrapy" to see available commands
原因是:在使用命令行startproject的时候,会自动生成scrapy.cfg。而使用命令行cmd启动爬虫时,crawl会去搜索cmd当前目录下的scrapy.cfg文件,官方文档中也进行了说明。找不到scrapy.cfg文件则认为没有该project。
解决方案:因此cd进入该dmoz项目的根目录,即scrapy.cfg文件在的目录,执行命令scrapy crawl dmoz
正常情况下得到的输出应该是:
2014-01-23 18:13:07-0400 [scrapy] info: scrapy started (bot: tutorial)
2014-01-23 18:13:07-0400 [scrapy] info: optional features available: ...
2014-01-23 18:13:07-0400 [scrapy] info: overridden settings: {}
2014-01-23 18:13:07-0400 [scrapy] info: enabled extensions: ...
2014-01-23 18:13:07-0400 [scrapy] info: enabled downloader middlewares: ...
2014-01-23 18:13:07-0400 [scrapy] info: enabled spider middlewares: ...
2014-01-23 18:13:07-0400 [scrapy] info: enabled item pipelines: ...
2014-01-23 18:13:07-0400 [dmoz] info: spider opened
2014-01-23 18:13:08-0400 [dmoz] debug: crawled (200) <get http://www.dmoz.org/computers/programming/languages/python/resources/> (referer: none)
2014-01-23 18:13:09-0400 [dmoz] debug: crawled (200) <get http://www.dmoz.org/computers/programming/languages/python/books/> (referer: none)
然而实际不是
报错提示二:
file "/library/frameworks/python.framework/versions/3.7/lib/python3.7/site-packages/scrapy/spiderloader.py", line 71, in load
raise keyerror("spider not found: {}".format(spider_name))
keyerror: 'spider not found: dmoz'
alicedemacbook-pro:tutorial alice$ scrapy crawl dmoz 2019-04-19 09:28:23 [scrapy.utils.log] info: scrapy 1.6.0 started (bot: tutorial) 2019-04-19 09:28:23 [scrapy.utils.log] info: versions: lxml 4.3.3.0, libxml2 2.9.9, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, twisted 18.7.0, python 3.7.3 (v3.7.3:ef4ec6ed12, mar 25 2019, 16:39:00) - [gcc 4.2.1 (apple inc. build 5666) (dot 3)], pyopenssl 18.0.0 (openssl 1.1.0i 14 aug 2018), cryptography 2.3.1, platform darwin-17.3.0-x86_64-i386-64bit traceback (most recent call last): file "/library/frameworks/python.framework/versions/3.7/lib/python3.7/site-packages/scrapy/spiderloader.py", line 69, in load return self._spiders[spider_name] keyerror: 'dmoz' during handling of the above exception, another exception occurred: traceback (most recent call last): file "/library/frameworks/python.framework/versions/3.7/lib/python3.7/site-packages/scrapy/spiderloader.py", line 71, in load raise keyerror("spider not found: {}".format(spider_name)) keyerror: 'spider not found: dmoz'
原因:定位的目录不正确,要进入到dmoz在的目录
解决方案:也比较简单,重新check目录进去即可
报错提示三:
file "/library/python/2.7/site-packages/twisted/internet/_sslverify.py", line 15, in <module>
from openssl._util import lib as pyopenssllib
importerror: no module named _util
alicedemacbook-pro:tutorial alice$ scrapy crawl dmoz 2018-08-06 22:25:23 [scrapy.utils.log] info: scrapy 1.5.1 started (bot: tutorial) 2018-08-06 22:25:23 [scrapy.utils.log] info: versions: lxml 4.2.4.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, twisted 18.7.0, python 2.7.10 (default, jul 15 2017, 17:16:57) - [gcc 4.2.1 compatible apple llvm 9.0.0 (clang-900.0.31)], pyopenssl 0.13.1 (libressl 2.2.7), cryptography unknown, platform darwin-17.3.0-x86_64-i386-64bit 2018-08-06 22:25:23 [scrapy.crawler] info: overridden settings: {'newspider_module': 'tutorial.spiders', 'spider_modules': ['tutorial.spiders'], 'robotstxt_obey': true, 'bot_name': 'tutorial'} traceback (most recent call last): file "/usr/local/bin/scrapy", line 11, in <module> sys.exit(execute()) file "/library/python/2.7/site-packages/scrapy/cmdline.py", line 150, in execute _run_print_help(parser, _run_command, cmd, args, opts) file "/library/python/2.7/site-packages/scrapy/cmdline.py", line 90, in _run_print_help func(*a, **kw) file "/library/python/2.7/site-packages/scrapy/cmdline.py", line 157, in _run_command t/ssl.py", line 230, in <module> from twisted.internet._sslverify import ( file "/library/python/2.7/site-packages/twisted/internet/_sslverify.py", line 15, in <module> from openssl._util import lib as pyopenssllib importerror: no module named _util
网上查了很久的资料,仍然无解。部分博主说是pyopenssl或scrapy的安装有问题,于是重新装了pyopenssl和scrapy,但还是报同样错误,实在不知道怎么解决了。
后面重装了pyopenssl和scrapy,貌似是解决了~
2019-04-19 09:46:37 [scrapy.core.engine] info: spider opened 2019-04-19 09:46:37 [scrapy.extensions.logstats] info: crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2019-04-19 09:46:39 [scrapy.core.engine] debug: crawled (403) <get http://www.dmoz.org/robots.txt> (referer: none) 2019-04-19 09:46:39 [scrapy.core.engine] debug: crawled (403) <get http://www.dmoz.org/computers/programming/languages/python/books/> (referer: none) 2019-04-19 09:46:40 [scrapy.spidermiddlewares.httperror] info: ignoring response <403 http://www.dmoz.org/computers/programming/languages/python/books/>: http status code is not handled or not allowed 2019-04-19 09:46:40 [scrapy.core.engine] debug: crawled (403) <get http://www.dmoz.org/computers/programming/languages/python/resources/> (referer: none) 2019-04-19 09:46:40 [scrapy.spidermiddlewares.httperror] info: ignoring response <403 http://www.dmoz.org/computers/programming/languages/python/resources/>: http status code is not handled or not allowed 2019-04-19 09:46:40 [scrapy.core.engine] info: closing spider (finished) 2019-04-19 09:46:40 [scrapy.statscollectors] info: dumping scrapy stats: {'downloader/request_bytes': 737, 'downloader/request_count': 3, 'downloader/request_method_count/get': 3, 'downloader/response_bytes': 2103, 'downloader/response_count': 3, 'downloader/response_status_count/403': 3, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2019, 4, 19, 1, 46, 40, 570939), 'httperror/response_ignored_count': 2, 'httperror/response_ignored_status_count/403': 2, 'log_count/debug': 3, 'log_count/info': 9, 'log_count/warning': 1, 'memusage/max': 65601536, 'memusage/startup': 65597440, 'response_received_count': 3, 'robotstxt/request_count': 1, 'robotstxt/response_count': 1, 'robotstxt/response_status_count/403': 1, 'scheduler/dequeued': 2, 'scheduler/dequeued/memory': 2, 'scheduler/enqueued': 2, 'scheduler/enqueued/memory': 2, 'start_time': datetime.datetime(2019, 4, 19, 1, 46, 37, 468659)} 2019-04-19 09:46:40 [scrapy.core.engine] info: spider closed (finished) alicedemacbook-pro:tutorial alice$
到此这篇关于python爬虫之scrapy环境搭建案例教程的文章就介绍到这了,更多相关python爬虫之scrapy环境搭建内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库
-
windows7 32、64位下python爬虫框架scrapy环境的搭建方法
-
VirtualBox CentOS7.7.1908 Python3.8 搭建Scrapy开发环境【图文教程】
-
Python爬虫之Scrapy环境搭建案例教程
-
【Python学习系列五】Python网络爬虫框架Scrapy环境搭建
-
Python 工具 之 Scrapy 环境搭建(Twisted插件下载安装),以及 Scrapy 框架的简单使用说明
-
Crawlab准备之python+scrapy环境搭建
-
【python爬虫】Pycharm+Scrapy+win10搭建scrapy开发环境+运行一个Demo
-
Python爬虫之Scrapy环境搭建
-
详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库