python - 从 BeautifulSoup 结果中获取表单 "action"

标签 python regex web-scraping beautifulsoup

我正在为一个网站编写一个 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

结果:

<form id="form_product_page" name="form_1362737440" action="/download/791055/164084/" method="get">
<input id="nojssubmit" type="submit" value="Download" />
</form>

的确,代码已经完成,这正是我开始所需要的。现在,我想知道应该以哪种方式从“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

最佳答案

您可以一步完成:

action = soup.find('form', id='form_product_page').get('action')

关于python - 从 BeautifulSoup 结果中获取表单 "action",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462826/

相关文章:

c++ - 通过 std::regex 从数学表达式制作树

python - 以编程方式解析网页(使用登录名/ssl)

javascript - 抓取一组包含混合内容的页面的最佳方法

python - Tensorflow 非极大值抑制

Python,open.system 函数 - 文件名中包含空格时出错

.net - Regex.Replace 中的 "or"运算符是否有理论表达式大小限制

python - python 在 float 前插入逗号

python - 类型错误 : unsupported operand type(s) for %: 'tuple' and 'str'

python - 如何使用 python mechanize 发送有效负载

python - BeautifulSoup 问题 : Get exact link url and Title