美丽的汤如何从物体中提取一根弦

2024-03-29 14:10:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学靓汤。我已经成功地追踪到了我需要的html行。 我的下一步是从这些行中提取一个Id值。在

查找行的代码如下所示:

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

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

^{pr2}$

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

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

任何帮助都将不胜感激!在


Tags: 对象代码resrcidimgsearchobject
2条回答

您需要确保在对象的源上执行regex搜索。你可以试试看:

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

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

您可以调整以下内容:

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]

相关问题 更多 >