如何在通过BeautifulSoup提取后通过正则表达式运行属性值



我有一个URL,我想解析它的一部分,特别是widgetid:

<a href="http://www.somesite.com/process.asp?widgetid=4530">Widgets Rock!</a>

我写了这个Python(我是Python的一个新手,版本是2.7):

import re
from bs4 import BeautifulSoup
doc = open('c:Python27some_xml_file.txt')
soup = BeautifulSoup(doc)

links = soup.findAll('a')
# debugging statements
print type(links[7])
# output: <class 'bs4.element.Tag'>
print links[7]
# output: <a href="http://www.somesite.com/process.asp?widgetid=4530">Widgets Rock!</a>
theURL = links[7].attrs['href']
print theURL
# output: http://www.somesite.com/process.asp?widgetid=4530
print type(theURL)
# output: <type 'unicode'>
is_widget_url = re.compile('[0-9]')
print is_widget_url.match(theURL)
# output: None (I know this isn't the correct regex but I'd think it
#         would match if there's any number in there!)

我想我在正则表达式中遗漏了一些东西(或者我对如何使用它们的理解),但我不明白。

谢谢你的帮助!

这个问题与BeautifulSoup无关。

问题是,正如文档所解释的,match只在字符串的开头匹配。由于要查找的数字位于字符串的末尾,因此它不会返回任何内容。

要在任何位置匹配一个数字,请使用search,您可能需要使用d实体来匹配数字。

matches = re.search(r'd+', theURL)

我认为你不想要重新-你可能想要:

from urlparse import urlparse, parse_qs
s = 'http://www.somesite.com/process.asp?widgetid=4530'
qs = parse_qs(urlparse(s).query)
if 'widgetid' in qs:
   # it's got a widget, a widget it has got...

使用urlparse:

from urlparse import urlparse, parse_qs
o = urlparse("http://www.somesite.com/process.asp?widgetid=4530")
if "widgetId" in parse_qs(o.query):
    # this is a 'widget URL'

最新更新