【问题标题】:BeautifulSoup get_text separate values with "<br>"BeautifulSoup get_text 用“<br>”分隔值
【发布时间】:2021-05-16 01:07:16
【问题描述】:

HTML:

"<td class='tdtl'><a class='col' href='detail.php?id=1' target='_blank''>List 1< br>detail 1</a></td>"
"<td class='tdtl'><a class='col' href='detail.php?id=2' target='_blank''>List 2< br>detail 2</a></td>"
"<td class='tdtl'><a class='col' href='detail.php?id=3' target='_blank''>List 3< br>detail 3</a></td>"
"<td class='tdtl'><a class='col' href='detail.php?id=4' target='_blank''>List 4< br>detail 4</a></td>"
"<td class='tdtl'><a class='col' href='detail.php?id=5' target='_blank''>List 5< br>detail 5</a></td>"

Python 编码:

for index in soup.select("col"):
    print(index.get_text())

结果:

第 1 行详细信息 1

第 2 行详细信息 2

第 3 行详细信息 3

第 4 行详细信息 4

第 5 行详细信息 5

如何检索变量中的“Line 1”和“detail 1”?

【问题讨论】:

  • 您确定您的&lt;br&gt;HTML 中看起来像&lt; br&gt;
  • 发布 HTML 代码,但在我的问题上看不到“
    ”标签。因此,添加备用只是为了展示。
  • 初始 HTML 缺少 标记。

标签: python python-3.x beautifulsoup


【解决方案1】:

如果标签的格式始终为&lt; br&gt;,那么您可以使用简单的拆分:

the_lists = []
the_details = []

for index in soup.select("a.col"):
    my_text = index.get_text().split('< br>')
    the_lists.append(my_text[0])
    the_details.append(my_text[1])
    
print(the_lists) # ['List 1', 'List 2', 'List 3', 'List 4', 'List 5'] 
print(the_details) # ['detail 1', 'detail 2', 'detail 3', 'detail 4', 'detail 5']

编辑

要管理其他格式的&lt;br&gt; 标签,例如&lt; br&gt; &lt;br&gt; &lt;br &gt;,您可以使用正则表达式:

the_lists = []
the_details = []

for index in soup.select("a.col"):
    text = re.sub("<(\s*)br(\s*)>","<br>",index.get_text())
    my_text = text.split('<br>')
    the_lists.append(my_text[0])
    the_details.append(my_text[1])
    
print(the_lists)    
print(the_details)

【讨论】:

  • "
    " 可以使用空格,但不能拆分没有空格的"
    "。
  • 在您的示例中,您没有
    而只有
    。但是,您可以使用正则表达式对其进行管理。查看更新