如何使用美丽的汤在两个不同的标签之间获取价值?

How to get value between two different tags using beautiful soup?

我需要在下面的代码片段中提取结束标签和
标签之间的数据:

<td><b>First Type :</b>W<br><b>Second Type :</b>65<br><b>Third Type :</b>3</td>

我需要的是:W, 65, 3

但问题是这些值也可以为空,比如-

<td><b>First Type :</b><br><b>Second Type :</b><br><b>Third Type :</b></td>

如果存在空字符串,我想获取这些值

我尝试使用 nextSiblingfind_next('br') 但它 returned

 <br><b>Second Type :</b><br><b>Third Type :</b></br></br>

<br><b>Third Type :</b></br>

如果标签之间不存在值 (W, 65, 3)

</b> and <br> 

我只需要 return 如果这些标签之间没有任何内容,它应该是一个空字符串。

我会搜索 td 对象,然后使用 regex 模式来过滤您需要的数据,而不是在 find_all 方法中使用 re.compile

像这样:

import re
from bs4 import BeautifulSoup

example = """<td><b>First Type :</b>W<br><b>Second Type :</b>65<br><b>Third 
Type :</b>3</td>
<td><b>First Type :</b><br><b>Second Type :</b>69<br><b>Third Type :</b>6</td>"""

soup = BeautifulSoup(example, "html.parser")

for o in soup.find_all('td'):
    match = re.findall(r'</b>\s*(.*?)\s*(<br|</br)', str(o))
    print ("%s,%s,%s" % (match[0][0],match[1][0],match[2][0]))

此模式查找 </b> 标签和 <br></br> 标签之间的所有文本。 </br> 标签是在将 soup 对象转换为字符串时添加的。

这个例子输出:

W,65,3

,69,6

举个例子,如果其中一个正则表达式匹配项为空,您可以将 return 更改为空字符串。

我认为这可行:

from bs4 import BeautifulSoup
html = '''<td><b>First Type :</b>W<br><b>Second Type :</b>65<br><b>Third Type :</b>3</td>'''
soup = BeautifulSoup(html, 'lxml')
td = soup.find('td')
string = str(td)
list_tags = string.split('</b>')
list_needed = []
for i in range(1, len(list_tags)):
    if list_tags[i][0] == '<':
        list_needed.append('')
    else:
        list_needed.append(list_tags[i][0])
print(list_needed)
#['W', '65', '3']

因为你想要的值总是在标签结束之后,所以很容易用这种方式捕获它们,不需要重新。

我会通过 </b> 标签策略使用 <b> 标签,查看它们 next_sibling 包含的信息类型。

我会检查他们的 next_sibling.string 是否不是 None,并相应地附加列表 :)

>>> html = """<td><b>First Type :</b><br><b>Second Type :</b>65<br><b>Third Type :</b>3</td>"""

>>> soup = BeautifulSoup(html, "html.parser")
>>> b = soup.find_all("b")
>>> data = []
>>> for tag in b:
        if tag.next_sibling.string == None:
            data.append(" ")
        else:
            data.append(tag.next_sibling.string)
>>> data 
[' ', u'65', u'3'] # Having removed the first string

希望对您有所帮助!

In [5]: [child for child in soup.td.children if isinstance(child, str)]
Out[5]: ['W', '65', '3']

那些文本和标签是 td 的子项,您可以使用 contents(list) 或 children(generator)

访问它们
In [4]: soup.td.contents
Out[4]: 
[<b>First Type :</b>,
 'W',
 <br/>,
 <b>Second Type :</b>,
 '65',
 <br/>,
 <b>Third Type :</b>,
 '3']

然后你可以通过测试它是否是str

的实例来获取文本