python数据采集9-穿越网页表单与登录窗口进行采集

Python Requests库

虽然用 Python 的标准库也可以控制网页表单,但是有时用一点儿语法糖可以让生活更甜
蜜。当你想做比 urllib 库能够实现的基本 GET 请求更多的事情时,可以看看 Python 标准
库之外的第三方库

Python 的标准库 urllib2 为你提供了大多数 HTTP 功能,但是它的 API 非常差劲。这是
因为它是经过许多年一步步建立起来的——不同时期要面对的是不同的网络环境。于是
为了完成最简单的任务,它需要耗费大量的工作(甚至要重写整个方法)。

提交一个基本表单

<form method="post" action="processing.php">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<input type="submit" value="Submit">
</form>

import requests
params = {'firstname': 'Ryan', 'lastname': 'Mitchell'}
r = requests.post("http://pythonscraping.com/files/processing.php", data=params)
print(r.text)



<form action="http://post.oreilly.com/client/o/oreilly/forms/
quicksignup.cgi" id="example_form2" method="POST">
<input name="client_token" type="hidden" value="oreilly" />
<input name="subscribe" type="hidden" value="optin" />
<input name="success_url" type="hidden" value="http://oreilly.com/store/
newsletter-thankyou.html" />
<input name="error_url" type="hidden" value="http://oreilly.com/store/
newsletter-signup-error.html" />
<input name="topic_or_dod" type="hidden" value="1" />
<input name="source" type="hidden" value="orm-home-t1-dotd" />
<fieldset>
<input class="email_address long" maxlength="200" name=
"email_addr" size="25" type="text" value=
"Enter your email here" />
<button alt="Join" class="skinny" name="submit" οnclick=
"return addClickTracking('orm','ebook','rightrail','dod'
);" value="submit">Join</button>
</fieldset>
</form>

单选按钮、复选框和其他输入

<form method="GET" action="someProcessor.php">
<input type="someCrazyInputType" name="thing1" value="foo" />
<input type="anotherCrazyInputType" name="thing2" value="bar" />
<input type="submit" value="Submit" />
</form>

对应的 Python 参数就是:

{'thing1':'foo', 'thing2':'bar'}

提交文件和图像

虽然上传文件在网络上很普遍,但是对于网络数据采集其实不太常用。但是,如果你想为
自己网站的文件上传功能写一个测试实例,也是可以实现的。不管怎么说,掌握工作原理
总是有用的。

<form action="processing2.php" method="post" enctype="multipart/form-data">
Submit a jpg, png, or gif: <input type="file" name="image"><br>
<input type="submit" value="Upload File">
</form>

处理登录和cookie

import requests
params = {'username': 'Ryan', 'password': 'password'}
126 | 第 9 章
r = requests.post("http://pythonscraping.com/pages/cookies/welcome.php", params)
print("Cookie is set to:")
print(r.cookies.get_dict())
print("-----------")
print("Going to profile page...")
r = requests.get("http://pythonscraping.com/pages/cookies/profile.php",
cookies=r.cookies)
print(r.text)
posted @ 2019-01-05 09:24  孙中明  阅读(280)  评论(0编辑  收藏  举报