Python Post 形成防刮保护

标签 python web-scraping

尝试使用 Python 从网站上抓取内容,该网站具有使用用户名和密码的简单表单例份验证,但也有一个名为“foil”的隐藏字段,其中包含每次加载页面时随机生成的字符串.为了成功登录,该值必须包含在帖子的内容标题中。我试过在登录页面加载后删除随机字符串,但仍然将我重定向回登录。我有有效网站的有效用户名和密码,但它偶尔会更新,我想在发生变化时给自己发送一封电子邮件。这是我到目前为止一直在使用的代码...

import urllib, urllib2, cookielib,subprocess

url='https://example.com/login.asp'

username='blah'
password='blah'

request = urllib2.Request(url)
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
preData = opener.open(request).readlines()
for line in preData:
    if("foil" in line):
        foils = line.split('"')
        notFoiled = foils[3]

query_args={'location':'','qstring':'','absr_ID':notFoiled,'id':username,'pin':password,'submit':'Sign In'}
requestWheader = urllib2.Request('https://example.com/login.asp')
requestWheader.add_data(urllib.urlencode(query_args))
print 'Request method after data :', requestWheader.get_method()

print
print 'OUTGOING DATA:'
print requestWheader.get_data()

print
print 'SERVER RESPONSE:'
print urllib2.urlopen(requestWheader).read()
rawRes = urllib2.urlopen(requestWheader).read()

表单看起来像这样......

<form name="loginform" method="post" action="https://example.com/login.asp?x=x&amp;&amp;pswd=">
<input type=hidden name="location" value="">
<input type=hidden name="qstring" value="">
<input type=hidden name="absr_ID" value="">
<input type=hidden name="foil" value="91fcMO">
<input type="text" name="id" maxlength="80" size="21" value="" mask="" desc="ID" required="true">
<input type="submit" name="submit" value="Sign In" onClick="return checkForm(loginform)">
<input type="password" name="pin" size="6" maxlength="6" desc="Pin" required="true">

最佳答案

您导入了 cookielib,但您似乎没有使用任何 CookieJar:

jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))

然后使用相同的开启器来获取初始表单和提交登录表单。我假设这是一种基于 cookie 的保护,其中来自 foil 字段的值必须与 header 中出现的 cookie 相匹配。

我在您的代码中注意到的另一件事是您将 notFoiled 分配给 absr_ID 而不是 foil。这是故意的吗?

另外,请帮自己一个忙,使用 html5libBeautifulSoup 而不是手动解析 HTML。

关于Python Post 形成防刮保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734307/

相关文章:

python - Selenium PhantomJS 抛出 EelementNotVisible,而 Firefox 在组合框选择期间完全正常

python-3.x - Webkit_server(从 python 的 dryscrape 调用)在访问每个页面时使用越来越多的内存。如何减少使用的内存?

python - 从网站捕获视频流到文件中

python - 如何在 Bokeh 中添加多行 x 轴标签?

python - Pandas 数据框加入重叠的时间范围

python - 在 Pandas 中将 csv 转换为 txt 时,电话号码中丢失 "+"

java - 如何剥离从网络收获中获得的文本的一部分

Python cgi 奇怪的行为

html - 从网球运动员事件页面读取所有 html 表

python - 如何从雅虎获取历史ESG数据?