使用BeautifulSoup获取<li>标签内的数据

2024-05-13 21:27:05 发布

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

ul中有3个li元素。《美人汤》并没有表现出李氏元素内的文字。 3个li元素包含一个机构的位置、电话号码和传真号码。在

<ul>
    <li class="spacer">
        <span>
            Location:
        </span>
        <br></br>
        1500 S. 1st Avenue
        <br></br>
        Yuma, AZ 85364
    </li>
    <li class="spacer">
        <span>
            Phone Number:
        </span>
        <br></br>
        928-373-4700
    </li>
    <li class="spacer">
        <span>
            Fax Number:
        </span>
        <br></br>
        928-343-8864
    </li>

我的剧本是:

^{pr2}$

输出为:

<li class="spacer"><span>Location:</span> </li>

我可以得到特定的li元素,但是没有位置数据。由于某种原因它被省略了。在

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


Tags: br元素number机构电话号码locationliul
2条回答

它不是关于BeautifulSoup的版本,而是关于differences between underlying parsersBeautifulSoup使用的:

Beautiful Soup presents the same interface to a number of different parsers, but each parser is different. Different parsers will create different parse trees from the same document.

演示:

>>> soup = BeautifulSoup(text, 'html.parser')
>>> print soup.find('li', attrs={'class': 'spacer'})
<li class="spacer"><span>Location:</span> </li>

>>> soup = BeautifulSoup(text, 'html5lib')
>>> print soup.find('li', attrs={'class': 'spacer'})
<li class="spacer"><span>Location:</span> <br/>1500 S. 1st Avenue<br/>Yuma, AZ 85364</li>

>>> soup = BeautifulSoup(text, 'lxml')
>>> print soup.find('li', attrs={'class': 'spacer'})
<li class="spacer"><span>Location:</span> 1500 S. 1st AvenueYuma, AZ 85364</li>

如您所见,不同的解析器-不同的结果。在

{t{1}当你显式指定解析器时^

If you don’t specify anything, you’ll get the best HTML parser that’s installed. Beautiful Soup ranks lxml’s parser as being the best, then html5lib’s, then Python’s built-in parser.

我不确定你用的是什么版本。在我的带有beauthoulsoup4.3.2和Py2.7的机器中,输出是

<li class="spacer"><span>Location:</span> 1500 S. 1st AvenueYuma, AZ 85364</li>

相关问题 更多 >