V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
pive
V2EX  ›  问与答

本人正在学习 Python 爬虫,想模拟登录本网站( www.v2ex.com)但一直不成功,大神们帮忙看看,谢谢了。

  •  
  •   pive · 2017-02-20 10:19:58 +08:00 · 1438 次点击
    这是一个创建于 2644 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    import requests
    from bs4 import BeautifulSoup

    login_url=r'https://www.v2ex.com/signin'
    headers = {
    "content-type":"application/x-www-form-urlencoded",
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
    'Origin': 'https://www.v2ex.com',
    'Referer': 'https://www.v2ex.com/signin'
    }
    userName='pive'
    password='******'
    s=requests.Session()
    res=s.get(login_url,headers=headers)
    soup=BeautifulSoup(res.content,"html.parser")
    once=soup.find("input",{"name":"once"})["value"]
    formUserName=soup.find("input",type="text")["name"]
    formPassword=soup.find("input",type="password")["name"]
    print(once+"\n"+userName+"\n"+password)
    post_data={
    formUserName:userName,
    formPassword:password,
    "once":once,
    "next":"/"
    }
    s.post(login_url,post_data,headers=headers)
    f = s.get('https://www.v2ex.com/settings',headers=headers)
    with open('v2ex.html',"wb") as v2ex:
    v2ex.write(f.content)
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2411 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 14:30 · PVG 22:30 · LAX 07:30 · JFK 10:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.