scrapy project xxxx
scrapy genspider xxxxx "http://www.xx.com"
编写items.py 明确要提取的数据
编写spiders/xxx.py 编写爬虫文件处理请求和响应
编写pipelines.py 编写管道文件,处理spider返回item数据
编写settings.py 启用管道组建,以及其他相关设置
执行爬虫
hr.tencent.com
创建spider模板
scrapy genspider tencent "tencent.com"
执行爬虫命令
scrapy crawl tencent
++++++++++++++++++++++++++++++++++
scrapy startproject Douyu
scrapy genspider douyu "douyucdn.cn"
item.py
nickname=scrapy.Field()
imagelink=scrapy.Field()
douyucdn.cn
baseUrl="http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset="
offset=0
start_urls=[baseUrl+str(offset)]
spider.py
def parse(self,response):
data=json.loads(response.body)
#print(data)
if len(data)==0:
return
for dat in data:
print(dat["nickname"])
print(dat["avatar_mid"])
item=DouyuItem()
item['nickname']=dat['nickname']
item['avatar_mid']=dat['avatar_mid']
yield item
self.offset+=20
yield scrapy.Request(self.baseUrl+str(self.offset),callback=self.parse)
pipline
ImagesPipeline
def get_media_requests(self,item,info):
image_link=item['imagelink']
yield scrapy.Request(image_link)
def process_item(self,item,spider):
return item
def item_complete(self,results,item,info):
#print(relust)
#print(***)
image_path=[x["path"] for ok ,x in resluts if ok]
os.rename(images_store+image_path[0],images_store+item["nickname"]+".jpg")
return item
setting.py
IMAGES_STORE=""
Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36
Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_0 like Mac OSX; en-us) AppleWebKit/525.18.1(KHTML,like Gecko) Version/3.1.1Mobile/5A347 Safari/525.200
TOBOTSTXT_OBEY=False
path=[x["path"] for ok,x in resluts if ok]
cd douyue
scrapy crawl Douyu
scrapy 笔记
安装 scrapy
pip install scrapy
pip install pypiwin32
1、针对于文本检索的TF-IDF算法
2、针对于链接传递权重的链接算法:Pagerank
3、针对于链接再计算的:HITS算法
4、针对于链接相关度的:Hilltop算法
5、让链接计算更加灵活的:SALSA算法
6、更加完善的Pagerank算法
7、基于用户点击行为的结果性排序
import scrapy
from qsbk.items import QsbkItem
class QsbkSpiderSpider(scrapy.Spider):
name='qsbk_spider'
allowed_domains=['qiushibaike.com']
start_urls=['https://www.qiushibaike.com/text/page/1']
def parse(self,response):
duanzidivs=response.xpth("//div[@id='content-left']/div")
for duanzidiv in duanzidivs:
author=duanzidiv.xpath(".//h2/text()").get().strip()
content=duanzidiv.xpath(".//div[@class='content']//text()").getall()
content="".join(content).strip()
item=QsbkItem(author=author,content=content)
#duanzi={"author":author,"content":content}
yield item #duanzi
pipelines.py
import json
class QsbkPipeline(object):
def __init__(self):
self.fp=open("duanzi.join","w",encoding="utf-8")
def open_spider(self,spider):
print("爬虫开始")
pass
def process_item(self,item,spider):
item_json=json.dumps(item)
item_json=json.dumps(dict(item),ensure_ascii=False)
self.fp.write(item_json+'\n')
return item
def close_spider(self,spider):
self.fp.close()
print("爬虫结束")
settings.py
打开注释
ITEM_PIPELINES={
'qsbk.pipelines.QsbkPipeline':300
}
items.py
import scrapy
class QsbkItem(scrapy.Item):
author=scrapy.Field()
content=scrapy.Field()
糗事百科爬虫笔记
1.response 是一个scrapy.http.response.html.HtmlResponse 对象,可以用xpath 和 css来提取数据
2.提取出来的数据是一个Selector 或者是 SelectList对象,如果想要获得其中的其中的字符串,那么应该执行 getall 或者 get 方法。
3.getall 方法:获取Selector 中的所有文本,返回的是一个列表
4.get 方法:获取的是Selector 中的第一个文本,返回的是一个str类型
5.如果数据解析回来,要传给pipline处理,那么可以使用yield来返回,或者是收集所有的item最后统一用return 返回
6.item:建议在‘item.py’中定义好模型,以后就不用字典
7.pipline:这个是专门用来保存数据的。其中有三个方法是经常用的:
open_spider(self,spider)
process_item(self,item,spider)
close_spider(slef,spider)
要激活pipline,应该在‘settings.py’中,设置‘ITEM_PIPELINES’。
·····························································
ITEM_PIPELINES={
'qsbk.pipelines.QsbkPipeline':300
}
·····························································
以json行的形式重写管道
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline(object):
def __init__(self):
self.fp=open("duanzi.json",'wb')
self.exporter=JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
def open_spider(self,spider):
print("爬虫开始。。。")
def process_item(self,item,spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.fp.close()
print('爬虫结束了。。。')
以json文件形式重写管道
from scrapy.exporters import JonsItemExporter
class QsbkPipeline(object):
def __init__(self):
self.fp=open("duanzi.json",'wb')
self.exporter=JsonItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
self.exporter.start_exporting()
def open_spider(self,spider):
print("爬虫开始了")
def process_item(self,item,spider):
self.exporters.export_item(item)
return item
def close_spider(self,spider):
self.exporter.finish_exporting()
self.fp.close()
print('爬虫结束了....')
重写 spider 使得蜘蛛能连续爬取下一页的数据
················································
class qsbk_spider
name
start_urls
domain
def parse(self,response):
//提取列表集合
//遍历每一项
//提取要的数据
//yield 返回
//提取下一页的链接
//如果有,就发起请求
//如果没有,结束蜘蛛
···················································
class QsbkSpiderSpider(scrapy.Spider):
name='qsbk_spider'
allowed_domains=['qiushibaike.com']
start_urls=['https://www.qiushibaike.com/text/page/1/']
base_domain="https://www.qiushibaike.com"
def parse(self,response):
duanzidivs=response.xpath("//div[@id='content-left']/div")
for duanzidiv in duanzidivs:
author=duanzidiv.xpath(".//h2/text()").get().strip()
content=duanzidiv.xpath(".//div[@class='content']//text()").getall()
content="".join(content).strip()
item=QsbkItem(author=author,content=content)
yield item
next_url=response.xpath("//ul[@class='pagination']/li/[last()/a/@href]").get()
if not next_url:
return
else yield scrapy.Request(self.base_domain+next_url,callback=slef.parse)
scrapy genspider -c crawl [爬虫名字][域名]
##### CrawlSpider:
需要使用LinkExtractor和Rule.这两个东西决定爬虫的具体走向。
1. allow设置规则的方法:要能够限制在我们想要的url上面。不要跟其他的ur1产生相同
的正则表达式即可。
2.什么情况下使用follow:如果在爬取页面的时候,需要将满足当前条件的url再进行跟
进,那么就设置为True.否则设置为Fasle.
3.什么情况下该指定callback: 如果这个url对应的页面,只是为了获取更多的url,并不
需要里面的数据,那么可以不指定callback.如果想要获取url对应页面中的数据,那么就
需要指定一个callback.
非体址Scrapy Shell:
I
1.可以方便我们做一些数据提取的测试代码。
2.如果想要执行scrapy命令,那么毫无疑问,肯定是要先进入到scrapy所在的环境中。
3.如果想要读取某个项目的配置信息,那么应该先进入到这个项目中。再执行scrapy
shell"命令,|
数据存入mysql
class JianshuSpiderPipeline(object):
def __init__:
dbparam={
'host':'127.0.0.1',
'port':'3306',
'user':'root',
'password':'root',
'database':'jianshu2'
'charset':'utf-8'
}
self.conn=pymysql.connect(**dbparams)
self.cursor=self.conn.cursor()
self._sql=None
def process_item(self,item,spider):
self.cursor.execute(self.sql,(item['title'],item['content'],item['author']))
self.conn.commit()
return item
@property
def sql(self):
if not self._sql:
self.sql:="""
insert into article(id,title,content) values(null,%s,%s,$s,$s)
"""
return self._sql
return self._sql
异步入口
class JianshuTwistedPipeline(object):
def __init__(self):
dbparam={
'host':'',
'port':'',
'user':'',
'password':'',
'database':'',
'charset':'utf8',
'cursorclass':cursors.DictCursor
}
self.dbpool=adapi.ConnectionPool('pymysql',**dbparams)
self._sql=None
@property
def sql(self):
if not self._sql:
self._sql="""
insert into() values(null,%s,%s,%s,%s,%s)
"""
return self._sql
return self._sql
def process_item(self,item,spider):
defer=self.dbpool.runInteraction(self.insert_item,item)
defer.addErrback(self.handle_error,item,spider)
def insert_item(self,cursor,item):
cursor.execute(self.sql,(item['title'],item['content'],item['author'],item['avatar']))
def handle_error(self,error,item,spider):
print('='*10+"error",item,spider):
print(error)
start.py
from scrapy import cmdline
cmdline.execute("scrapy craw swf".split())
到处python 虚拟环境的依赖
pip freeze > requirements.txt
rz 命令 可以打开本地文件上传对话框
pip install -r requirements.txt
虚拟环境安装
pip install virtualenvwrapper
which python3
mkvirtualenv -p /usr/bin/python3 crawler -env
http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&offset=100
https://www.bilibili.com/video/av57909837/?p=2