[2018-07-28]使用scrapy模拟登录豆瓣(有验证码)并获取登录后信息【半成品】

···python
import scrapy
from scrapy.http import Request, FormRequest
import urllib.request

class DbSpider(scrapy.Spider):
name = “db”
allowed_domains = [“douban.com”]
”’
start_urls = [‘http://douban.com/’]
”’
headers = {“User-Agent”: “Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36”}

def start_requests(self):
    return [Request("https://accounts.douban.com/login",
                    callback=self.parse,
                    meta={"cookiejar": 1},
                    )]

def parse(self, response):
    captcha = response.xpath("//img[@id='captcha_image']/@src").extract()
    if len(captcha) > 0:
        print("此时有验证码")
        localpath = "G:/Chiduru/python/crawler/scrapy_data/douban_captcha/captchar.jpg"
        urllib.request.urlretrieve(captcha[0], filename=localpath)
        print("请查看本地验证码图片并输入验证码")
        captcha_value = input()
        data = {
            "form_email": "xxxxxx",
            "form_password": "xxxxxx",
            "captcha-solution": str(captcha_value),
            "redir": "https://www.douban.com/people/179723151/"  # 登录后要返回的页面
        }
    else:
        print("此时没有验证码")
        data = {
            "form_email": "xxxxxx",
            "form_password": "xxxxxx",
            "redir": "https://www.douban.com/people/179723151/"
        }
        url = "https://accounts.douban.com/login"
    print("登录中。。。。。。")
    return [FormRequest.from_response(response,
                                      meta={"cookiejar": response.meta["cookiejar"]},
                                      headers=self.headers,
                                      formdata=data,
                                      callback=self.next,
                                      )]

def next(self, response):
    print("此时已经登录完成并爬取了个人中心的数据")
    title = response.xpath("/html/head/title/text()").extract()
    note = response.xpath("//div[@class='note']/text()").extract()
    print(title[0])
    print(note[0])

···

cmd终端执行scrapy crawl db之后
[output]
···
2018-07-28 20:21:53 [scrapy.utils.log] INFO: Scrapy 1.3.3 started (bot: douban)
2018-07-28 20:21:53 [scrapy.utils.log] INFO: Overridden settings: {‘BOT_NAME’: ‘douban’, ‘NEWSPIDER_MODULE’: ‘douban.spiders’, ‘SPIDER_MODULES’: [‘douban.spiders’]}
2018-07-28 20:21:53 [scrapy.middleware] INFO: Enabled extensions:
[‘scrapy.extensions.corestats.CoreStats’,
‘scrapy.extensions.telnet.TelnetConsole’,
‘scrapy.extensions.logstats.LogStats’]
2018-07-28 20:21:53 [scrapy.middleware] INFO: Enabled downloader middlewares:
[‘scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware’,
‘scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware’,
‘scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware’,
‘scrapy.downloadermiddlewares.useragent.UserAgentMiddleware’,
‘scrapy.downloadermiddlewares.retry.RetryMiddleware’,
‘scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware’,
‘scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware’,
‘scrapy.downloadermiddlewares.redirect.RedirectMiddleware’,
‘scrapy.downloadermiddlewares.cookies.CookiesMiddleware’,
‘scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware’,
‘scrapy.downloadermiddlewares.stats.DownloaderStats’]
2018-07-28 20:21:53 [scrapy.middleware] INFO: Enabled spider middlewares:
[‘scrapy.spidermiddlewares.httperror.HttpErrorMiddleware’,
‘scrapy.spidermiddlewares.offsite.OffsiteMiddleware’,
‘scrapy.spidermiddlewares.referer.RefererMiddleware’,
‘scrapy.spidermiddlewares.urllength.UrlLengthMiddleware’,
‘scrapy.spidermiddlewares.depth.DepthMiddleware’]
2018-07-28 20:21:53 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-07-28 20:21:53 [scrapy.core.engine] INFO: Spider opened
2018-07-28 20:21:53 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-07-28 20:21:53 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-07-28 20:21:53 [scrapy.core.engine] DEBUG: Crawled (403) <GET https://accounts.douban.com/login> (referer: None)
此时没有验证码
登录中。。。。。。
2018-07-28 20:21:53 [scrapy.core.scraper] ERROR: Spider error processing <GET https://accounts.douban.com/login> (referer: None)
Traceback (most recent call last):
File “C:\Users\chiduru\Anaconda3\lib\site-packages\twisted\internet\defer.py”, line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File “G:\Chiduru\python\crawler\scrapy_pract\douban\douban\spiders\db.py”, line 48, in parse
callback=self.next,
File “C:\Users\chiduru\Anaconda3\lib\site-packages\scrapy\http\request\form.py”, line 45, in from_response
form = _get_form(response, formname, formid, formnumber, formxpath)
File “C:\Users\chiduru\Anaconda3\lib\site-packages\scrapy\http\request\form.py”, line 71, in _get_form
raise ValueError(“No <form> element found in %s” % response)
ValueError: No <form> element found in <403 https://accounts.douban.com/login>
2018-07-28 20:21:53 [scrapy.core.engine] INFO: Closing spider (finished)
2018-07-28 20:21:53 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{‘downloader/request_bytes’: 222,
‘downloader/request_count’: 1,
‘downloader/request_method_count/GET’: 1,
‘downloader/response_bytes’: 248,
‘downloader/response_count’: 1,
‘downloader/response_status_count/403’: 1,
‘finish_reason’: ‘finished’,
‘finish_time’: datetime.datetime(2018, 7, 28, 12, 21, 53, 981476),
‘log_count/DEBUG’: 2,
‘log_count/ERROR’: 1,
‘log_count/INFO’: 7,
‘response_received_count’: 1,
‘scheduler/dequeued’: 1,
‘scheduler/dequeued/memory’: 1,
‘scheduler/enqueued’: 1,
‘scheduler/enqueued/memory’: 1,
‘spider_exceptions/ValueError’: 1,
‘start_time’: datetime.datetime(2018, 7, 28, 12, 21, 53, 510715)}
2018-07-28 20:21:53 [scrapy.core.engine] INFO: Spider closed (finished)
···

scrapy crawl db –nolog:
此时没有验证码
登录中。。。。。。

why????
I have no idea

    原文作者:Chiduru
    原文地址: https://www.jianshu.com/p/95ff9d95a776
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞