上周用了一周的时间学习了Python和Scrapy,实现了从0到1完整的网页爬虫实现。研究的时候很痛苦,但是很享受,做技术的嘛。

首先,安装Python,坑太多了,一个个爬。由于我是windows环境,没钱买mac, 在安装的时候遇到各种各样的问题,确实各种各样的依赖。

安装教程不再赘述。如果在安装的过程中遇到 ERROR:需要windows c/c++问题,一般是由于缺少windows开发编译环境,晚上大多数教程是安装一个VisualStudio,太不靠谱了,事实上只要安装一个WindowsSDK就可以了。

下面贴上我的爬虫代码:

爬虫主程序:

# -*- coding: utf-8 -*-

import scrapy

from scrapy.http import Request

from zjf.FsmzItems import FsmzItem

from scrapy.selector import Selector

# 圈圈:情感生活

class MySpider(scrapy.Spider):

#爬虫名

name = "MySpider"

#设定域名

allowed_domains = ["nvsheng.com"]

#爬取地址

start_urls = []

#flag

x = 0

#爬取方法

def parse(self, response):

item = FsmzItem()

sel = Selector(response)

item['title'] = sel.xpath('//h1/text()').extract()

item['text'] = sel.xpath('//*[@class="content"]/p/text()').extract()

item['imags'] = sel.xpath('//div[@id="content"]/p/a/img/@src|//div[@id="content"]/p/img/@src').extract()

if MySpider.x == 0:

page_list = MySpider.getUrl(self,response)

for page_single in page_list:

yield Request(page_single)

MySpider.x += 1

yield item

#init: 动态传入参数

#命令行传参写法: scrapy crawl MySpider -a start_url="http://some_url"

def __init__(self,*args,**kwargs):

super(MySpider,self).__init__(*args,**kwargs)

self.start_urls = [kwargs.get('start_url')]

def getUrl(self, response):

url_list = []

select = Selector(response)

page_list_tmp = select.xpath('//div[@class="viewnewpages"]/a[not(@class="next")]/@href').extract()

for page_tmp in page_list_tmp:

if page_tmp not in url_list:

url_list.append("http://www.nvsheng.com/emotion/px/" + page_tmp)

return url_list

PipeLines类

# -*- coding: utf-8 -*-

# Define your item pipelines here

#

# Don't forget to add your pipeline to the ITEM_PIPELINES setting

# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

from zjf import settings

import json,os,re,random

import urllib.request

import requests, json

from requests_toolbelt.multipart.encoder import MultipartEncoder

class MyPipeline(object):

flag = 1

post_title = ''

post_text = []

post_text_imageUrl_list = []

cs = []

user_id= ''

def __init__(self):

MyPipeline.user_id = MyPipeline.getRandomUser('37619,18441390,18441391')

#process the data

def process_item(self, item, spider):

#获取随机user_id,模拟发帖

user_id = MyPipeline.user_id

#获取正文text_str_tmp

text = item['text']

text_str_tmp = ""

for str in text:

text_str_tmp = text_str_tmp + str

# print(text_str_tmp)

#获取标题

if MyPipeline.flag == 1:

title = item['title']

MyPipeline.post_title = MyPipeline.post_title + title[0]

#保存并上传图片

text_insert_pic = ''

text_insert_pic_w = ''

text_insert_pic_h = ''

for imag_url in item['imags']:

img_name = imag_url.replace('/','').replace('.','').replace('|','').replace(':','')

pic_dir = settings.IMAGES_STORE + '%s.jpg' %(img_name)

urllib.request.urlretrieve(imag_url,pic_dir)

#图片上传,返回json

upload_img_result = MyPipeline.uploadImage(pic_dir,'image/jpeg')

#获取json中保存图片路径

text_insert_pic = upload_img_result['result']['image_url']

text_insert_pic_w = upload_img_result['result']['w']

text_insert_pic_h = upload_img_result['result']['h']

#拼接json

if MyPipeline.flag == 1:

cs_json = {"c":text_str_tmp,"i":"","w":text_insert_pic_w,"h":text_insert_pic_h}

else:

cs_json = {"c":text_str_tmp,"i":text_insert_pic,"w":text_insert_pic_w,"h":text_insert_pic_h}

MyPipeline.cs.append(cs_json)

MyPipeline.flag += 1

return item

#spider开启时被调用

def open_spider(self,spider):

pass

#sipder 关闭时被调用

def close_spider(self,spider):

strcs = json.dumps(MyPipeline.cs)

jsonData = {"apisign":"99ea3eda4b45549162c4a741d58baa60","user_id":MyPipeline.user_id,"gid":30,"t":MyPipeline.post_title,"cs":strcs}

MyPipeline.uploadPost(jsonData)

#上传图片

def uploadImage(img_path,content_type):

"uploadImage functions"

#UPLOAD_IMG_URL = "http://api.qa.douguo.net/robot/uploadpostimage"

UPLOAD_IMG_URL = "http://api.douguo.net/robot/uploadpostimage"

# 传图片

#imgPath = 'D:\pics\http___img_nvsheng_com_uploads_allimg_170119_18-1f1191g440_jpg.jpg'

m = MultipartEncoder(

# fields={'user_id': '192323',

# 'images': ('filename', open(imgPath, 'rb'), 'image/JPEG')}

fields={'user_id': MyPipeline.user_id,

'apisign':'99ea3eda4b45549162c4a741d58baa60',

'image': ('filename', open(img_path , 'rb'),'image/jpeg')}

)

r = requests.post(UPLOAD_IMG_URL,data=m,headers={'Content-Type': m.content_type})

return r.json()

def uploadPost(jsonData):

CREATE_POST_URL = http://api.douguo.net/robot/uploadimagespost

reqPost = requests.post(CREATE_POST_URL,data=jsonData)

def getRandomUser(userStr):

user_list = []

user_chooesd = ''

for user_id in str(userStr).split(','):

user_list.append(user_id)

userId_idx = random.randint(1,len(user_list))

user_chooesd = user_list[userId_idx-1]

return user_chooesd

字段保存Items类

# -*- coding: utf-8 -*-

# Define here the models for your scraped items

#

# See documentation in:

# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class FsmzItem(scrapy.Item):

# define the fields for your item here like:

# name = scrapy.Field()

title = scrapy.Field()

#tutor = scrapy.Field()

#strongText = scrapy.Field()

text = scrapy.Field()

imags = scrapy.Field()

在命令行里键入

scrapy crawl MySpider -a start_url=www.aaa.com

这样就可以爬取aaa.com下的内容了

以上这篇Python下使用Scrapy爬取网页内容的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

scrapy 中不同页面的拼接_Python下使用Scrapy爬取网页内容的实例相关推荐

  1. scrapy 中不同页面的拼接_scrapy官方文档提供的常见使用问题

    Scrapy与BeautifulSoup或lxml相比如何? BeautifulSoup和lxml是用于解析HTML和XML的库.Scrapy是一个用于编写Web爬虫的应用程序框架,可以抓取网站并从中 ...

  2. scrapy 中不同页面的拼接_scrapy使用技巧总结

    1. scrapy运行过程概述 scrapy是一个基于python的网络爬虫框架,它读取对指定域名的网页request请求,截取对应域名的返回体,开发者可以编写解析函数,从返回体中抓取自己需要的数据, ...

  3. scrapy中集成selenium+浏览器池实现selenium的并发爬取LCSC网站中非结构化表格数据+异步存储进mysql+完整代码

    爬取https://lcsc.com/products/Connectors_365.html这个网址下所有的表格数据. 蓝色的都是要爬取的子页面,要爬取子页面里面的表格数据 ,表格数据如下: 右上角 ...

  4. python爬虫爬图片教程_python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  5. python爬虫爬取教程_python爬虫实战之爬取京东商城实例教程

    前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧. 主要工具 scrapy BeautifulSoup requests 分析步骤 1. ...

  6. 微博话题下的数据爬取

    1.前言 新浪微博中,一个话题下各个媒体或用户发表在平台发表的信息是舆情研究的一个很重要的数据来源,这里记录一下一个话题下数据的爬取方式,以"#美国疫情#"话题为例. 2.话题下数 ...

  7. 利用python爬取租房信息_Python爬虫实战(1)-爬取“房天下”租房信息(超详细)

    #前言html 先看爬到的信息:python 今天主要用到了两个库:Requests和BeautifulSoup.因此我先简单的说一下这两个库的用法,提到的都是此文须要用到的.编程 #Requests ...

  8. php抓取网页内容实例,详解php中抓取网页内容的实例

    php中抓取网页内容的实例详解 方法一: 使用file_get_contents方法实现$url = "http://news.sina.com.cn/c/nd/2016-10-23/doc ...

  9. php抓取网页内容实例,php中抓取网页内容的实例详解

    php中抓取网页内容的实例详解 方法一: 使用file_get_contents方法实现 $url = "http://news.sina.com.cn/c/nd/2016-10-23/do ...

  10. Crawler之Scrapy:数据挖掘必备的scrapy框架之最完整爬取网页内容攻略

    相关文章推荐 Scrapy:Python3版本上安装数据挖掘必备的scrapy框架详细攻略(二最完整爬取网页内容信息攻略) 目录 scrapy框架之最完整爬取网页内容攻略 scrapy框架之最完整爬取 ...

最新文章

  1. 【c语言】求三个数的最小数
  2. 单击“登录”后,用户名和密码显示在地址栏中,不安全
  3. 2月第4周中国五大顶级域名总量减1.8万 美国增10.8万
  4. inspinia前端模板怎样编写消息提示框点击确定后的回调方法
  5. [Database] 数据库范式理论
  6. Robotframework与unittest对比
  7. Android启动(Booting)
  8. 前端JavaScript基础知识点
  9. [机器学习] 面试常见问题+解析汇总
  10. (13) css浮动补充
  11. php生成图片文件流,php 如何把图片转化为字节流存储到数据库?
  12. 随想录(动态库的特点)
  13. row_number() over使用方法
  14. (轉貼) 如何解決MegaCore IP 6.0安裝時-6001的錯誤? (IC Design) (MegaCore)
  15. SRM 515 DIV1 550pt
  16. 免费下载 [discuz!插件] 404页死链优化SEO V2.6
  17. [分享]下载电影文件英文标识的含义
  18. d3 企业图谱 仿天眼查 企查查
  19. 创客必备!树莓派知识大扫盲
  20. Python3.X使用Cython调用C/C++

热门文章

  1. C#开源爬虫NCrawler源代码解读以及将其移植到python3.2(4)
  2. 追求--MarsCoara
  3. javascript-----日历控件
  4. netty中ChannelHandler执行顺序案例详解
  5. Idea的svn新建分支,切换分支,合并分支
  6. 设计模式 ( 四 ) 抽象工厂模式
  7. Java中使用正则表达式校验字符串
  8. Juniper SSG20 Config DHCP Server
  9. linux性能监测工具
  10. Mysql三种备份,mysqdump,xtrabackup工具,基于lvm-snapshot快照备份等。