用于HTML解析的Python正则表达式(BeautifulSoup)

标签 python regex screen-scraping

我想获取 HTML 中隐藏输入字段的值。

<input type="hidden" name="fooId" value="12-3456789-1111111111" />

我想用 Python 编写一个正则表达式,它将返回 fooId 的值,前提是我知道 HTML 中的行遵循以下格式

<input type="hidden" name="fooId" value="**[id is here]**" />

有人可以提供一个 Python 示例来解析值的 HTML 吗?

最佳答案

对于这种特殊情况,BeautifulSoup 比正则表达式更难编写,但它更健壮......我只是为 BeautifulSoup 示例做出贡献,因为你已经知道要使用哪个正则表达式:-)

from BeautifulSoup import BeautifulSoup

#Or retrieve it from the web, etc. 
html_data = open('/yourwebsite/page.html','r').read()

#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId.attrs[2][1] #The value of the third attribute of the desired tag 
                          #or index it directly via fooId['value']

关于用于HTML解析的Python正则表达式(BeautifulSoup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391/

相关文章:

python - 用于发布到 Google+ 的简单 Python 代码

python - 抓取网页并需要选择正确的选择器

python - 将多个html文件抓取到CSV

python - 在 Django 模板中显示抓取的结果

python - 与未排序数据相交的 matplotlib 图

python - 从 subprocess.Popen 进行流式传输并使用两个子命令时出现死锁

python - 如何使用 map 将字典中的字符串小写?

c# - 正则表达式匹配重复组只捕获一个组

regex - 如果不存在空格,请在符号后添加空格?

java - 允许使用逗号和句点的正则表达式