python spider 发送post请求

上一章节,已经能够获取网页内容。这里需要实现发送post请求。

参考网上的例子,选择重写start_requests(self)方法:

1
2
3
4
5
6
7
8
def (self):
url = 'http://query.shenzhentong.com:8080/sztnet/qryCard.do'
yield scrapy.FormRequest(
url=url,
formdata={"cardno": "698474623"},
callback=self.parse_page
)

自定义回调函数:

1
2
3
def parse_page(self, response):
print response.text
pass

以上是就是发送post的代码。

执行后可获取对应卡号的信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<table cellspacing='1' cellpadding='2' class='tableact'>
<tr>
<td bgcolor='#E4F2F3'>
卡号:
</td>
<td bgcolor='#FFFFFF'>
698474623
</td>
<td bgcolor='#E4F2F3' id='cardRealAmt' width="10%" nowrap>
卡内余额(截止到2018-05-11 19:31:31):
</td>
<td bgcolor='#FFFFFF' align='right'>
4.20元
</td>
<td bgcolor='#E4F2F3' id='expDate' width="10%" nowrap>
卡有效截止日期:
</td>
<td bgcolor='#FFFFFF' align='right'></td>
</tr>
</table>