如何使用正则表达式解析HTML标签? [英] How do I use regular expressions to parse HTML tags?
本文介绍了如何使用正则表达式解析HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想知道如何使用正则表达式(最好在python中)推断html元素的值.
Was wondering how I would extrapolate the value of an html element using a regular expression (in python preferably).
例如,<a href="http://google.com"> Hello World! </a>
我将使用什么正则表达式从上面的html中提取Hello World!
?
What regex would I use to extract Hello World!
from the above html?
推荐答案
但是 BeautifulSoup 是一个方便的库
But BeautifulSoup is a handy library.
>>> from BeautifulSoup import BeautifulSoup
>>> html = '<a href="http://google.com"> Hello World! </a>'
>>> soup = BeautifulSoup(html)
>>> soup.a.string
u' Hello World! '
例如,这将在此页面上打印出链接:
This, for instance, would print out links on this page:
import urllib2
from BeautifulSoup import BeautifulSoup
q = urllib2.urlopen('https://stackoverflow.com/questions/3884419/')
soup = BeautifulSoup(q.read())
for link in soup.findAll('a'):
if link.has_key('href'):
print str(link.string) + " -> " + link['href']
elif link.has_key('id'):
print "ID: " + link['id']
else:
print "???"
输出:
Stack Exchange -> http://stackexchange.com
log in -> /users/login?returnurl=%2fquestions%2f3884419%2f
careers -> http://careers.stackoverflow.com
meta -> http://meta.stackoverflow.com
...
ID: flag-post-3884419
None -> /posts/3884419/revisions
...
这篇关于如何使用正则表达式解析HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文