html特定字段表紅,提取字段HTML表单的名称 – Python

本文介绍了一种方法,利用Python中的lxml库从指定HTML页面的特定表单(form2)中提取所有输入字段的名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设有一个链接“http://www.someHTMLPageWithTwoForms.com”,它基本上是一个有两种形式的HTML页面(比如Form 1和Form 2).我有这样的代码……

import httplib2

from BeautifulSoup import BeautifulSoup, SoupStrainer

h = httplib2.Http('.cache')

response, content = h.request('http://www.someHTMLPageWithTwoForms.com')

for field in BeautifulSoup(content, parseOnlyThese=SoupStrainer('input')):

if field.has_key('name'):

print field['name']

这将返回属于我的HTML页面的表单1和表单2的所有字段名称.有什么方法我只能获得属于特定表单的字段名称(仅限表单2)?

解决方法:

使用lxml进行这种解析也很容易(我个人更喜欢使用BeautifulSoup,因为它支持Xpath).例如,以下代码段将打印属于名为“form2”的表单的所有字段名称(如果有的话):

# you can ignore this part, it's only here for the demo

from StringIO import StringIO

HTML = StringIO("""

""")

# here goes the useful code

import lxml.html

tree = lxml.html.parse(HTML) # you can pass parse() a file-like object or an URL

root = tree.getroot()

for form in root.xpath('//form[@name="form2"]'):

for field in form.getchildren():

if 'name' in field.keys():

print field.get('name')

标签:python,parsing

来源: https://codeday.me/bug/20190626/1294869.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值