pive
V2EX  ›  问与答

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

  •  
  •   pive · Feb 20, 2017 · 1897 views
    This topic created in 3392 days ago, the information mentioned may be changed or developed.
    #!/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)
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   931 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:08 · PVG 06:08 · LAX 15:08 · JFK 18:08
    ♥ Do have faith in what you're doing.