python - 解析 HTML 时遇到问题

标签 python html jython

我环顾四周,发现了一些如何在 python 中拆分文本的示例,但我的示例存在问题。这是我要解析的内容:

<img alt="" src="http://example.com/servlet/charting?base_color=grey&amp;chart_width=288&amp;chart_height=160&amp;chart_type=png&amp;chart_style=manufund_pie&amp;3DSet=true&amp;chart_size=small&amp;leg_on=left&amp;static_xvalues=10.21,12.12,43.12,12.10,&amp;static_labels=blue,red,green,purple">

这是我尝试过的:

dict(kvpair.split('=') for kvpair in variableIwantToParse.split('&'))

我收到错误“ValueError:字典更新序列元素 #0 的长度为 5;需要 2”

我也尝试使用 variableIwantToParse.strip('&') 但是当我尝试打印 variableIwantToParse 时,它​​一次只替换了一个字母。

我确信这很容易,但似乎无法弄清楚如何解析它。我基本上希望 10.21、12.12、43.12、12.10 与蓝色、红色、绿色、紫色相关联(按照显示的顺序)

非常感谢您的帮助(如果这太简单了,我深表歉意......我就是一辈子都想不出解析这个的命令):-)

最佳答案

使用内置的 urlparse module , 不要自己做这些拆分。

>>> import urlparse
>>> url_to_parse = "http://example.com/servlet/charting?base_color=grey&amp;chart_width=288&amp;chart_height=160&amp;chart_type=png&amp;chart_style=manufund_pie&amp;3DSet=true&amp;chart_size=small&amp;leg_on=left&amp;static_xvalues=10.21,12.12,43.12,12.10,&amp;static_labels=blue,red,green,purple"
>>> parsed_url = urlparse.urlparse(url_to_parse)
>>> query_as_dict = urlparse.parse_qs(parsed_url.query)
>>> print query_as_dict
{'chart_size': ['small'], 'base_color': ['grey'], 'chart_style': ['manufund_pie'], 'chart_height': ['160'], 'static_xvalues': ['10.21,12.12,43.12,12.10,'], 'chart_width': ['288'], 'static_labels': ['blue,red,green,purple'], 'leg_on': ['left'], 'chart_type': ['png'], '3DSet': ['true']}

如果您使用的 Python 版本低于 2.6,则必须导入 cgi module .改为这样做:

>>> import urlparse
>>> import cgi
>>> parsed_url = urlparse.urlparse(url_to_parse)
>>> query_as_dict = cgi.parse_qs(parsed_url.query)
>>> print query_as_dict
{'chart_size': ['small'], 'base_color': ['grey'], 'chart_style': ['manufund_pie'], 'chart_height': ['160'], 'static_xvalues': ['10.21,12.12,43.12,12.10,'], 'chart_width': ['288'], 'static_labels': ['blue,red,green,purple'], 'leg_on': ['left'], 'chart_type': ['png'], '3DSet': ['true']}

然后将它们关联到字典,使用提供的字典构造函数和 zip .

>>> print dict(zip( query_as_dict['static_labels'][0].split(','), query_as_dict['static_xvalues'][0].split(',')))
{'blue': '10.21', 'purple': '12.10', 'green': '43.12', 'red': '12.12'}

关于python - 解析 HTML 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5296336/

相关文章:

python - python字符串类在源代码中的位置

iphone - 如何在 iOS 应用程序中调用 python 脚本?

html - 这是一种纠正绝对 iframe 的 Internet Explorer View 的方法吗?

c# - HTMLAgilityPack SelectNodes 选择所有 <img> 元素

python - 在 jython 中导入 python 模块

jython - 使用 Pig 和 Python

python - 关闭当前文件/ View /显示而不保存或被要求这样做

python - 在 sql server 上运行 python(.py 脚本)

html - 欧洲的 hreflang 标签

java - Jython::PythonInterpreter 有哪些模块可用以及如何添加更多