Scrapy to zhihu

# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request, FormRequest
from scrapy.selector import Selector
import json
import os
from tutorial.items import ZhihuItem


class ZhihuSpider(scrapy.Spider):
    name = "zhihu"
    allowed_domains = ["zhihu.com"]
    pwd = os.path.split(os.path.realpath(__file__))[0]
    cookiesfilename = pwd + os.path.sep + "cookies.txt"
    start_urls = [
        "https://www.zhihu.com"
    ]

    def start_requests(self):
        cookies = self.load_cookies_from_mozilla(self.cookiesfilename)
        self.logger.info(cookies)
        for url in self.start_urls:
            yield Request(
                url,
                cookies=cookies,
                callback=self.after_login)

    def after_login(self, response):
        # 有/people/*鏈接說明登錄成功
        if not response.xpath('//a[re:test(@href, "/people/")]'):
            self.logger.info("登錄失敗")
            scrapy.shell.inspect_response(response, self)
            return None
        self.logger.info("登錄成功")
        # scrapy.shell.inspect_response(response, self)
        _xsrf = response.xpath('///*[@name="_xsrf"]/@value').extract_first()
        headers = response.request.headers
        headers["X-Xsrftoken"] = _xsrf
        return FormRequest(
            url="https://www.zhihu.com/topic/19552832/followers",
            headers=headers,
            formdata={"offset": "0"},
            meta={"offset": 0, "headers": headers},
            callback=self.get_followers)

    def get_followers(self, response):

        msg = json.loads(response.body_as_unicode())['msg']
        offset = response.meta["offset"] + 20
        if not msg[0] == 0:
            sel = Selector(text=msg[-1])
        else:
            return None
        for i in sel.xpath('//a[@class="zg-link author-link"]'):
            name = i.xpath('text()').extract_first()
            href = i.xpath("@href").extract_first()
            yield Request(
                url="https://www.zhihu.com" + href,
                meta={"name": name, "href": href},
                callback=self.get_about
            )
        mi_ids = sel.xpath('///*[@class="zm-person-item"]/@id').extract()
        yield FormRequest(
            url="https://www.zhihu.com/topic/19552832/followers",
            headers=response.meta["headers"],
            formdata={"offset": str(offset), "start": mi_ids[-1].split('-')[-1]},
            meta={"offset": offset, "headers": response.meta["headers"]},
            callback=self.get_followers)

    def get_about(self, response):
        sel = Selector(text=response.body_as_unicode())
        item = ZhihuItem()
        item["name"] = response.meta["name"]
        item["href"] = response.meta["href"]
        item["location"] = sel.xpath('///*[@class="location item"]/@title').extract_first()
        item["business"] = sel.xpath('///*[@class="business item"]/@title').extract_first()
        if sel.xpath('///*[@class="icon icon-profile-male"]'):
            item["gender"] = "male"
        elif sel.xpath('///*[@class="icon icon-profile-female"]'):
            item["gender"] = "female"
        else:
            item["gender"] = "unknown"
        item["employment"] = sel.xpath('///*[@class="employment item"]/@title').extract_first()
        item["position"] = sel.xpath('///*[@class="position item"]/@title').extract_first()
        item["education"] = sel.xpath('///*[@class="education item"]/@title').extract_first()
        item["major"] = sel.xpath('///*[@class="education-extra item"]/@title').extract_first()

        yield item

    def load_cookies_from_mozilla(self, filename):
        cookies = []
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                cookies_list = line.split()
                cookies.append(dict(
                    name=cookies_list[-2],
                    value=cookies_list[-1],
                ))
        return cookies
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末源梭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子酒奶,更是在濱河造成了極大的恐慌删咱,老刑警劉巖屑埋,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異痰滋,居然都是意外死亡摘能,警方通過查閱死者的電腦和手機(jī)续崖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來团搞,“玉大人严望,你說我怎么就攤上這事÷呖郑” “怎么了像吻?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長复隆。 經(jīng)常有香客問我拨匆,道長,這世上最難降的妖魔是什么挽拂? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任惭每,我火速辦了婚禮,結(jié)果婚禮上轻局,老公的妹妹穿的比我還像新娘。我一直安慰自己样刷,他們只是感情好仑扑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著置鼻,像睡著了一般镇饮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上箕母,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天储藐,我揣著相機(jī)與錄音,去河邊找鬼嘶是。 笑死钙勃,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的聂喇。 我是一名探鬼主播辖源,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼希太!你這毒婦竟也來了克饶?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤誊辉,失蹤者是張志新(化名)和其女友劉穎矾湃,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體堕澄,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡邀跃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年霉咨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坞嘀。...
    茶點(diǎn)故事閱讀 39,764評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡躯护,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出丽涩,到底是詐尸還是另有隱情棺滞,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布矢渊,位于F島的核電站继准,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏矮男。R本人自食惡果不足惜移必,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望毡鉴。 院中可真熱鬧崔泵,春花似錦、人聲如沸猪瞬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陈瘦。三九已至幌甘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間痊项,已是汗流浹背锅风。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鞍泉,地道東北人皱埠。 一個(gè)月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像咖驮,于是被迫代替她去往敵國和親漱逸。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容