美丽的汤 - 如何从对象中提取字符串

时间:2013-06-18 21:13:02

标签: python beautifulsoup

我正在学习美丽的汤。我成功地追踪了我需要的html行。 我的下一步是从这些行中提取Id值。

查找行的代码如下所示:

object = soup_station.find('img',{'src': re.compile("^Controls")})

如果我现在打印对象,我会得到这个,例如:

<img src="Controls/RiverLevels/ChartImage.jpg?Id=471&amp;ChartType=Histogram" id="StationDetails_Chart1_chartImage" alt="Current river level" />

我想在上面一行中提取的部分是"471"之后的Id=

我尝试在对象上使用re.search,但似乎对象不是文本。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

您可以调整以下内容:

s = '<img src="Controls/RiverLevels/ChartImage.jpg?Id=471&amp;ChartType=Histogram" id="StationDetails_Chart1_chartImage" alt="Current river level" />'

from bs4 import BeautifulSoup
import re
from urlparse import urlsplit, parse_qs


soup = BeautifulSoup(s)
# find the node with a src starting with Controls
node = soup.find('img',{'src': re.compile("^Controls")})
# Break up the url in the src attribute
url_split = urlsplit(node['src'])
# Parse out the query parameter from the url
qs = parse_qs(url_split.query)
# Display the value for `Id`
print qs['Id'][0]

答案 1 :(得分:0)

您希望确保在对象的源上执行正则表达式搜索。你可以尝试一下:

import re
ele = soup_station.find('img')
src = ele['src']

match = re.search(r'\?Id=(\d+)', src)
ele_id = match.group(1)
相关问题