【问题标题】:How to run an attribute value through a regular expression after extracting via BeautifulSoup?通过 BeautifulSoup 提取后如何通过正则表达式运行属性值?
【发布时间】:2012-07-24 08:15:27
【问题描述】:

我有一个要解析的 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:\Python27\some_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!)

我认为我在正则表达式中遗漏了一些东西(或者我对如何使用它们的理解),但我无法弄清楚。

感谢您的帮助!

【问题讨论】:

  • 之所以建议urlparse,是因为它已经制定了查询字符串解析逻辑——例如,如果你得到一个带有更多参数的 URL,它仍然可以工作。

标签: python regex url unicode beautifulsoup


【解决方案1】:

这个问题与 BeautifulSoup 无关。

问题在于,由于the documentation explainsmatch 只匹配字符串的开头。由于您要查找的数字位于字符串的末尾,因此它不返回任何内容。

要匹配任意位置的数字,请使用 search - 您可能希望使用 \d 实体来匹配数字。

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

【讨论】:

  • 非常感谢。这让我难倒了好一阵子!
  • 不要使用re,使用urlparse
  • @Tichodroma,这是因为效率(使用 urlparse 而不是正则表达式)吗?
  • 不,因为 Python 来自 with batteries included
【解决方案2】:

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

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...

【讨论】:

  • 谢谢你。我猜正则表达式是我最喜欢的解析锤。
【解决方案3】:

使用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'

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 2021-08-17
    • 2019-10-06
    • 2018-10-17
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多