如果模以POST登录网站各位好,我是PYTHON新手,想请问大家一下,如何用python模拟post登录,因为我在抓取数据
如果模以POST登录网站
各位好,我是PYTHON新手,想请问大家一下,如何用python模拟post登录,因为我在抓取数据的过程中,有些数据登录后才能获取数据,特来这里请教一下大家,非常感谢!
[解决办法]
看下这两个模块:
urllib
urllib2
[解决办法]
用下面这段代码改一下就好了
- Python code
def query(self): try: url = httplib.urlsplit(self.url) conn = httplib.HTTPConnection(url.netloc) conn.connect() #conn.set_debuglevel(1) if self.data: conn.putrequest("POST", self.url) conn.putheader("Content-Length", len(self.data)) conn.putheader("Content-Type", "application/x-www-form-urlencoded") else: conn.putrequest("GET", self.url, None) conn.putheader("Content-Length", 0) conn.putheader("Connection", "close") conn.endheaders() if self.data: conn.send(self.data) f = conn.getresponse() if f: self.response = f.read() f.close() conn.close()
[解决办法]
import urllib,urllib2,cookielib
def post3():
# for mail.sina.com.cn
cj = cookielib.CookieJar()
url_login = 'http://mail.sina.com.cn/cgi-bin/login.cgi'
body = (('logintype','login'), ('u','username'),
('psw', '********'))
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#opener.addheaders = [('User-agent', 'Opera/9.23')]
opener.addheaders = [('User-agent',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]
urllib2.install_opener(opener)
req=urllib2.Request(url_login,urllib.urlencode(body))
u=urllib2.urlopen(req)
print u.read().decode('utf-8').encode('gbk')下午,试了一下python的http 相关类的方法,用上述代码登录新浪邮箱,试了一段时间,比较关键的是User-agent,上边两种浏览器的agent都支持。估计python默认的User-agent得不到sina.com的验证。
python写这种http method代码还是蛮方便的。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://iihero.cn (亿熊实验室)
Welcome to (iihero lab)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 