学习的课本为《python网络数据采集》,大部分代码来此此书。
大多数网页表单都是由一些HTML 字段、一个提交按钮、一个在表单处理完之后跳转的“执行结果”(表单属性action 的值)页面构成。虽然这些HTML 字段通常由文字内容构成,但是也可以实现文件上传或其他非文字内容。这些都为抓取数据的阻碍所以放在了前面。废话不多说开搞。
1.HTTP基本接入认证
在发明cookie 之前,处理网站登录最常用的方法就是用HTTP 基本接入认证(HTTP basicaccess authentication)
importrequestsfrom requests.auth importAuthBasefrom requests.auth importHTTPBasicAuth
auth= HTTPBasicAuth('ryan', 'password')
r= requests.post(url="http://pythonscraping.com/pages/auth/login.php", auth=auth)print(r.text)
虽然这看着像是一个普通的POST 请求,但是有一个HTTPBasicAuth 对象作为auth 参数传递到请求中。显示的结果将是用户名和密码验证成功的页面(如果验证失败,就是一个拒绝接入页面)。
2.一般表单处理
表单源码:
First name:
Last name:
注意一下:首先,两个输入字段的名称是firstname 和lastname,这一点非常重要。字段的名称决定了表单被确认后要被传送到服务器上的变量名称。如果你想模拟表单提交数据的行为,你就需要保证你的变量名称与字段名称是一一对应的。其次注意表单的真实行为其实发生在processing.php(绝对路径是http://pythonscraping.com/files/processing.php)。表单的任何POST 请求其实都发生在这个页面上,并非表单本身所在的页面。
python语句:
importrequests
# 将提交的信息设置成字典
params= {'firstname': 'Ryan', 'lastname': 'Mitchell'}
# 找到post请求,data填入你要提交的字典
r= requests.post("http://pythonscraping.com/files/processing.php", data=params)print(r.text)
3.看个代码稍微多点的
并不需要看懂每个代码的意思,只要知道你需要那些信息就可以(这句写在前面)
html:
"value="submit">Join
虽然第一次看这些会觉得恐怖,但是大多数情况下你只需要关注两件事:
• 你想提交数据的字段名称(在这个例子中是email_addr)
• 表单的action 属性,也就是表单提交后网站会显示的页面(在这个例子中是http://post.oreilly.com/client/o/oreilly/forms/quicksignup.cgi)把对应的信息增加到请求信息中,运行代码即可:
importrequests
params= {'email_addr': 'ryan.e.mitchell@gmail.com'}
r= requests.post("http://post.oreilly.com/client/o/oreilly/forms/quicksignup.cgi", data=params)
print(r.text)
4.提交文件和图像
html:
Upload a file!
Submit a jpg, png, or gif:
python:
importrequests
files= {'uploadFile': open('../files/Python-logo.png', 'rb')}
r= requests.post("http://pythonscraping.com/pages/processing2.php",
files=files)print(r.text)
用selenium来处理表单
这里需要设置webdriver
from selenium importwebdriverfrom selenium.common.exceptions importTimeoutExceptionfrom selenium.webdriver.support.ui importWebDriverWaitfrom selenium.webdriver.support importexpected_conditions as ECfrom selenium.webdriver.common.keys importKeysimporttimefrom urllib.request importurlretrieve
driver=webdriver.Firefox() # 打开一个浏览器
# 下面是设置代理忽略掉就可以#profile = webdriver.FirefoxProfile()#profile.set_preference('network.proxy.type', 1)#profile.set_preference('network.proxy.http', '127.0.0.1')#profile.set_preference('network.proxy.http_port', 8080)#profile.update_preferences()#driver = webdriver.Firefox(firefox_profile=profile)
# 打开网址
driver.get("http://60.216.103.149/jwweb/sys/ValidateCode.aspx")
# 查看你需要输入的表单是否在frame中,如果在,你可能搜不到输入框的id,所以你需要跳转一下,如果没有下面一行代码可以忽略
driver.switch_to_frame('frm_login')
# 输入账号xxxx
driver.find_element_by_id("txt_admin").send_keys("xxxx")
# 键盘事件table键 跳转到密码输入框
driver.find_element_by_id("txt_admin").send_keys(Keys.TAB)
driver.find_element_by_id("txt_power").send_keys("xxxx")
# 找到登入按钮的id,设置点击事件提交表单
driver.find_element_by_id("btn_login").click()