title: scrapy踩坑記錄
tags: ['scrapy','python','post','request']
date: 2021-03-11
categories: "搬磚"
安裝了python3.8但是沒(méi)有pip
在ubuntu上從Python 3.4版和2.7.9版開(kāi)始律杠,總是可以使用ensurepip
模塊來(lái)引導(dǎo)啟動(dòng)pip
猖腕,具體如下:
C:\Users\Administrator>python -m ensurepip
Looking in links: c:\Users\ADMINI~1\AppData\Local\Temp\tmpcempbgwg
Processing c:\users\administrator\appdata\local\temp\tmpcempbgwg\setuptools-47.1
.0-py3-none-any.whl
Processing c:\users\administrator\appdata\local\temp\tmpcempbgwg\pip-20.1.1-py2.
py3-none-any.whl
Installing collected packages: setuptools, pip
Successfully installed pip-20.1.1 setuptools-47.1.0
爬蟲(chóng)https,不安全的問(wèn)題
Python2/3 解決訪問(wèn)Https時(shí)不受信任SSL證書(shū)問(wèn)題
ssl._create_default_context = ssl._create_unverified_context
安裝scrapy遇到錯(cuò)誤
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f2/16/3eb9c66a7bfb5220c7bcbaaac33d359fe8a157b028959cd210983749b2e0/Twisted-21.2.0-py3-none-any.whl (3.1 MB)
|███████████████████████████████▌| 3.0 MB 262 kB/s eta 0:00:01
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the p
ackage contents carefully; someone may have tampered with them.
Twisted[http2]>=17.9.0 from https://pypi.tuna.tsinghua.edu.cn/packages/f2/16/3eb9c66a7bfb5220c7bcbaaac33d359fe8a157b028959cd210983749b2e0/Twisted-21.2.0-py3-none-
any.whl#sha256=aab38085ea6cda5b378b519a0ec99986874921ee8881318626b0a3414bb2631e (from scrapy):
Expected sha256 aab38085ea6cda5b378b519a0ec99986874921ee8881318626b0a3414bb2631e
Got c9b2f7ffbc1fb53011ba7c6500d784a78ef9e1f8274fa472eebc1eab930b216b
換個(gè)pip的源解決了
(venv) C:\Users\Administrator\Desktop\爬蟲(chóng)項(xiàng)目文件夾\scrapyDemo>pip3 install scrapy -i https://pypi.mirrors.ustc.edu.cn/simple
使用python2 環(huán)境安裝scrapy使用的時(shí)候報(bào)錯(cuò)from contextlib import suppress
原因
因?yàn)槲抑鞍惭b過(guò)python3燎窘,我的環(huán)境中的queuelib
的版本為1.6.0恶复,是最新版本其爵,但是這個(gè)包剛剛好再1.6.0取消了對(duì)python2的支持界赔。
解決辦法
下載queuelib
1.5.0的whl空民,安裝一下设捐。
下載地址https://www.cnblogs.com/klb561/p/9271322.html
No module named 'scrapy.xlib'
# scrapy1.7版本及以前
from scrapy.xlib.pydispatch import dispatcher
# 之后
from pydispatch import dispatcher
scrapy 數(shù)據(jù)保存json文件
# pipelines
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 導(dǎo)入 JsonItemExporter
from scrapy.exporters import JsonItemExporter
import time
class SpiderPipeline(object):
# 構(gòu)造方法(初始化對(duì)象時(shí)執(zhí)行的方法)
def __init__(self):
# 使用 'wb' (二進(jìn)制寫(xiě)模式)模式打開(kāi)文件
time_str = str(time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(time.time())))
print time_str
self.json_file = open(time_str + '_data.json', 'wb')
# 構(gòu)建 JsonItemExporter 對(duì)象,設(shè)定不使用 ASCII 編碼层玲,并指定編碼格式為 'UTF-8'
self.json_exporter = JsonItemExporter(self.json_file, ensure_ascii=False, encoding='UTF-8')
# 聲明 exporting 過(guò)程 開(kāi)始号醉,這一句也可以放在 open_spider() 方法中執(zhí)行。
self.json_exporter.start_exporting()
# 爬蟲(chóng) pipeline 接收到 Scrapy 引擎發(fā)來(lái)的 item 數(shù)據(jù)時(shí)辛块,執(zhí)行的方法
def process_item(self, item, spider):
# 將 item 存儲(chǔ)到內(nèi)存中
self.json_exporter.export_item(item)
return item
def close_spider(self, spider):
# 聲明 exporting 過(guò)程 結(jié)束畔派,結(jié)束后,JsonItemExporter 會(huì)將收集存放在內(nèi)存中的所有數(shù)據(jù)統(tǒng)一寫(xiě)入文件中
self.json_exporter.finish_exporting()
# 關(guān)閉文件
self.json_file.close()
# settings
ITEM_PIPELINES = {
'NsmcSpider.pipelines.SpiderPipeline': 300,
}
其他方法
命令行執(zhí)行
scrapy crawl spider -o result.json -t json
crawl spider -o result.json -s FEED_EXPORT_ENCODING=UTF-8
爬蟲(chóng)速度慢或者速度不穩(wěn)定的另外一種解決辦法
把cookie給禁掉
custom_settings = {"COOKIES_ENABLED":False}
使用scrapy.http.Request
數(shù)據(jù)不全的問(wèn)題
記得加上報(bào)文頭
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",# 這一條一定要加上
}
出現(xiàn)錯(cuò)誤Filtered offsite request to
原因:allowed_domains
和實(shí)際采集的網(wǎng)頁(yè)有出入
解決辦法:
yield Request(url=home, method='get', headers=self.headers,dont_filter=True,
meta={"channel": response.meta["channel"], },
callback=self.parse_link)
加上dont_filter=True
或者 將allowed_domains
的內(nèi)容改一下润绵,改成一級(jí)域名父虑,能夠和后面的匹配的上。
報(bào)錯(cuò)Filtered duplicate request: GET xxx - no more duplicates
原因: 爬取的url重復(fù)了授药,所以RedisSpider模塊默認(rèn)會(huì)記錄爬過(guò)的url,會(huì)把后面出現(xiàn)以前爬過(guò)的url去掉呜魄,導(dǎo)致重新開(kāi)啟程序爬取之前爬過(guò)的url悔叽,都被去除掉后就爬不到東西。
解決辦法:
加上dont_filter=True
scrapy有一個(gè)基于鏈接的去重爵嗅,加上dont_filter=True
可以完整的采集娇澎,去重可以放到入庫(kù)的時(shí)候再處理。
ValueError: check_hostname requires server_hostname
可能是開(kāi)了代理
進(jìn)行請(qǐng)求的時(shí)候使用urlencode
進(jìn)行轉(zhuǎn)碼報(bào)錯(cuò)TypeError: not a valid non-string sequence or mapping object
使用quote_plus
禁止重定向
yield Request(url=final, method='get', headers=self.headers,cookies=cookie,
meta={"channel": response.meta["channel"], "start_hash": response.meta['start_hash'],
"dont_redirect":True,'handle_httpstatus_list': [302]},
callback=self.parse_item)