python - 在 Python 中使用 BeautifulSoup 解析 html

标签 python html beautifulsoup

我写了一些代码来解析html,但是结果不是我想要的:

import urllib2
html = urllib2.urlopen('http://dummy').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for definition in soup.findAll('span', {"class":'d'}):
definition = definition.renderContents()
print "<meaning>", definition
for exampleofuse in soup.find('span',{"class":'x'}):
    print "<exampleofuse>", exampleofuse, "<exampleofuse>"
print "<meaning>"

有什么方法可以在类属性为“d”或“x”时获取字符串?

下面的html代码是我要解析的:

<span class="d">calculated by adding several amounts together</span>
<span class="x">an average rate</span>
<span class="x">at an average speed of 100 km/h</span>
<span class="d">typical or normal</span>
<span class="x">average intelligence</span>
<span class="x">20 pounds for dinner is average</span>

那么,这就是我想要的结果:

<definition>calculated by adding several amounts together
    <example_of_use>an average rate</example_of_use>
    <example_of_use>at an average speed of 100 km/h</example_of_use>
</definition>
<definition>typical or normal
    <example_of_use>average intelligence</example_of_use>
    <example_of_use>20 pounds for dinner is average</example_of_use>
</definition>

最佳答案

是的,您可以获得 html 中的所有跨度,然后为每个检查“d”或“x”类,如果有,则打印它们。

这样的东西可能有用(未经测试):

for span in soup.findAll('span'):
    if span.find("span","d").string:
        print "<definition>" + span.find("span","d").string + "</definition>"
    elif span.find("span","x").string:
        print "<example>" + span.find("span","x").string + "</example>"

关于python - 在 Python 中使用 BeautifulSoup 解析 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396655/

相关文章:

python - 在 tkinter 上运行 voice_recognition 会导致卡住

jquery - 定位的 div 元素

python - Beautiful Soup 为特定的 div 找到 child

python - Python 3.8 上的 Youtube 搜索

python - django: grappelli: 路由失败

python - 如何使用可变宽度高斯在 python 中执行卷积?

python - 你如何在 Python 中读取文本文件的特定行?

javascript - 不要让广告出现在彼此附近 jquery

PHP Post 参数为空时通过验证

python - 如何使用 robobrowser 返回页面的 html