从BeautifulSoup结果中获取表单"动作"

sen*_*ion 2 python regex beautifulsoup web-scraping

我正在为一个网站编写一个Python解析器来自动完成一些工作,但我对Py的"re"模块(正则表达式)并不多,并且无法使其工作.

req = urllib2.Request(tl2)
req.add_unredirected_header('User-Agent', ua)
response = urllib2.urlopen(req)
try:
    html = response.read()
except urllib2.URLError, e:
    print "Error while reading data. Are you connected to the interwebz?!", e

soup = BeautifulSoup.BeautifulSoup(html)
form = soup.find('form', id='form_product_page')
pret = form.prettify()

print pret
Run Code Online (Sandbox Code Playgroud)

结果:

<form id="form_product_page" name="form_1362737440" action="/download/791055/164084/" method="get">
<input id="nojssubmit" type="submit" value="Download" />
</form>
Run Code Online (Sandbox Code Playgroud)

确实,代码已经完成,正是我需要的开始.现在,我想知道从"form"标签中提取"action"属性的方法.这只是我从BeautifulSoup响应中所需要的.

我尝试过使用form = soup.find('form', id='form_product_page').parent.get('action')但是结果是"无".我想要提取的是例如"/ download/791055/164084 /".链接的每个URL都有所不同.


变量(示例):
tl2 = http://example.com
ua = Mozilla Firefox/14.04

Cas*_*yte 8

您可以一步完成:

action = soup.find('form', id='form_product_page').get('action')
Run Code Online (Sandbox Code Playgroud)