Scrapy 爬取知乎用户信息

Stella981
• 阅读 754

程序逻辑图如下:

Scrapy 爬取知乎用户信息

登录模块(获取cookie):

# encoding=utf-8
import requests
import re
import sys
#设置请求头
headers={
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding':'gzip, deflate, sdch, br',
    'Accept-Language':'zh-CN,zh;q=0.8',
    'Connection':'keep-alive',
    'Host':'www.zhihu.com',
    'Origin':'https://www.zhihu.com',
    'Referer':'https://www.zhihu.com/',
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    'x-hd-token':'hello',
}


#下面写入账号密码

post_data={
    '_xsrf':'***',
    'password':'****',
    'captcha':'***',
    'phone_num':'*****',
}

req=requests.Session()

def login():
    page=req.get(url="https://www.zhihu.com/#signin",headers=headers)
    parser=re.compile(u'<input type="hidden" name="_xsrf" value="(.*?)"/>',re.S)
    xsrf=re.findall(parser,page.text)[0]
    headers['X-Xsrftoken']=xsrf
    post_data['_xsrf']=xsrf
    #下载验证码
    with open("../code.jpg",'wb') as w:
        p=req.get(url="https://www.zhihu.com/captcha.gif?r=1495546872530&type=login",headers=headers)
        w.write(p.content)

    code=input("请输入验证码:")
    if not code:
        sys.exit(1)
    post_data['captcha']=code
    res=req.post(url='https://www.zhihu.com/login/phone_num',data=post_data,headers=headers)
    print(res.text)
    return req

cookie=login().cookies.get_dict()
    

spiders如下:这里用re(正则表达式和xpath解析网页,不懂的同学可以花时间去学习一下)

# -*- coding: utf-8 -*-
import scrapy
from zhihu.items import *
import re
class ZhSpider(scrapy.Spider):
    name = 'zh'
    allowed_domains = ['zhihu.com']
    start_urls = ['http://zhihu.com/']
    url='http://www.zhihu.com/'
    start_urls=['ruan-fu-zhong-tong-zhi','mu-huan-98',
    'zeus871219','a-li-ai-di-10','dyxxg','hao-er-8',
    'liu-miao-miao-47-17','peng-chen-xi-39','song-ling-shi-liao-63-56']
    task_set=set(start_urls)
    tasked_set=set()


    def start_requests(self):
        while len(self.task_set)>0:
            print("**********start用户库**********")
            print(str(self.task_set))
            print("********************")
            id=self.task_set.pop()
            if id in self.tasked_set:
                print("已经存在的数据 %s" %(id))
                continue
            self.tasked_set.add(id)

            userinfo_url='https://www.zhihu.com/people/{}/answers'.format(id)
            user_item=UserItem()
            user_item['Id']=id
            user_item['Url']=userinfo_url
            yield scrapy.Request(
                userinfo_url,
                meta={"item":user_item},callback=self.User_parse,dont_filter=True
            )
            yield scrapy.Request(
                'https://www.zhihu.com/people/{}/followers'.format(id),
                callback=self.Add_user,dont_filter=True
            )
    
    def Add_user(self,response):
        sel=scrapy.selector.Selector(response)
       #<a class="UserLink-link" target="_blank" href="https://my.oschina.net/people/12321-89">12321</a>
        #//*[@id="Profile-following"]/div[2]/div[2]/div/div/div[2]/h2/div/span/div/div/a/@href
        #//*[@id="Popover-24089-95956-toggle"]
        #//*[@id="Popover-24089-95956-toggle"]/a
        #print(response.text)
        co=sel.xpath('//*[@id="root"]/div/main/div/div/div[2]').extract_first()
        patten=re.compile(u'<a class="UserLink-link" target="_blank" href="https://my.oschina.net/people/(.*?)">.*?</a>',re.S)
        l=re.findall(patten,co)
        #l=sel.xpath('//*[@id="Profile-following"]/div[2]/div[2]/div/div/div[2]/h2/div/span/div/div/a/@href')
        for i in l:
            if str(i) not in self.tasked_set and str(i) not in self.task_set:
                self.task_set.add(i)
                print("**********用户库**********")
                print(str(self.task_set))
                print("********************")

    def User_parse(self, response):
        item=response.meta["item"]
        sel=scrapy.selector.Selector(response)
        nick_name=sel.xpath('//*[@id="ProfileHeader"]/div/div[2]/div/div[2]/div[1]/h1/span[1]/text()').extract_first()
        print(nick_name)
        #item['Nick_name']=nick_name
        summary=sel.xpath('//*[@id="ProfileHeader"]/div/div[2]/div/div[2]/div[1]/h1/span[2]/text()').extract_first()
        print(summary)
        item['Summary']=summary
        item['Nick_name']=nick_name
        # print(sel.xpath( '//span[@class="location item"]/@title').extract_first())
        co=sel.xpath('//*[@id="ProfileHeader"]/div/div[2]/div/div[2]/div[2]').extract_first()
        # print("**********************")
        # print(co)
        # print('**********************')
        patten=re.compile(u'.*?</div>(.*?)<div.*?>',re.S)
        l=re.findall(patten,co)
        #print(str(l))
        print("**********************")
        print(str(l))
        item['Content']=str(l)
        print('**********************')
        yield item

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

import pymysql
class ZhihuPipeline(object):
    def process_item(self, item, spider):
        return item


class MysqlPipeline(object):
    def __init__(self):
        self.conn=pymysql.connect(
            host='localhost',   #本地127.0.0.1
            port=3306,          #默认3306端口
            user='root',        #mysql最高权限用户
            passwd='****',  #root用户密码
            db='zh',       #database name
            charset='utf8'
            )
    def process_item(self,item,spider):
        self._conditional_insert(self.conn.cursor(),item)#调用插入的方法
       # query.addErrback(self._handle_error,item,spider)#调用异常处理方法
        return item

    def _conditional_insert(self,tx,item):

        sql="insert into user(id,url,nick_name,summary,content) values(%s,%s,%s,%s,%s)"
        params=(item["Id"],item["Url"],item['Nick_name'],item['Summary'],item['Content'])
        tx.execute(sql,params)
        print('已经插入一条数据!')
        tx.close()
        self.conn.commit()
      #  self.conn.close()
        
    #错误处理方法
    def _handle_error(self, failue, item, spider):
        print(failue)

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
from scrapy import Field

class ZhihuItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

class UserItem(scrapy.Item):
    """
    知乎用户的用户名,居住地,所在行业,职业经历,教育经历,个人简介
    """
    Id=Field()
    Url=Field()
    Nick_name=Field()
    Summary=Field()
    # Home_Position=Field()
    # Compmany=Field()
    # Edu=Field()
    Content=Field()

middlewares模块:

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

# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from zhihu.getCookie import cookie
from scrapy import signals

class CookiesMiddleware(object):
    """ 换Cookie """
    def process_request(self, request, spider):
        #cookie = random.choice(cookies)
        request.cookies = cookie

class ZhihuSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

代码是单机的,操作无误的话,可以一直运行下去,理论上可以把所有用户都抓下来,我测试的时候设的俩秒比较慢,一个小时一俩万字段。爬取的数据如下

Scrapy 爬取知乎用户信息

项目地址:

github:https://github.com/nanxung/-Scrapy

码云:http://git.oschina.net/nanxun/zhihu

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
java——20171121
!(http://a.51jsoft.com/uploads/default/original/1X/c542896b094a42a5653fb75adf6cdacd6e35d12e.png)!(https://static.oschina.net/uploads/space/2017/1121/210719_G80Z_3715033.png)
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这