gpt4 book ai didi

python - join 如何在 python beautifulsoup 中工作

转载 作者:行者123 更新时间:2023-11-28 22:01:58 24 4
gpt4 key购买 nike

正在学习python和beautifulsoup,在网上看到这段代码:

from BeautifulSoup import BeautifulSoup, SoupStrainer
import re

html = ['<html><body><p align="center"><b><font size="2">Table 1</font></b><table><tr><td>1. row 1, cell 1</td><td>1. row 1, cell 2</td></tr><tr><td>1. row 2, cell 1</td><td>1. row 2, cell 2</td></tr></table><p align="center"><b><font size="2">Table 2</font></b><table><tr><td>2. row 1, cell 1</td><td>2. row 1, cell 2</td></tr><tr><td>2. row 2, cell 1</td><td>2. row 2, cell 2</td></tr></table></html>']
soup = BeautifulSoup(''.join(html))
searchtext = re.compile(r'Table\s+1',re.IGNORECASE)
foundtext = soup.find('p',text=searchtext) # Find the first <p> tag with the search text
table = foundtext.findNext('table') # Find the first <table> tag that follows it
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
try:
text = ''.join(td.find(text=True))
except Exception:
text = ""
print text+"|",
print

虽然其他一切都很清楚,但我无法理解连接是如何工作的。

    text = ''.join(td.find(text=True))

我尝试在 BS 文档中搜索 join,但我找不到任何东西,也找不到关于如何在 BS 中使用 join 的在线帮助。

请告诉我该线路的工作原理。谢谢!

PS:以上代码来自另一个stackoverflow页面,不是我的功课:) How can I find a table after a text string using BeautifulSoup in Python?

最佳答案

''.join() 是一个 python 函数,不是特定于 BS 的任何东西。它让您可以使用字符串作为连接值来连接序列:

>>> '-'.join(map(str, range(3)))
'0-1-2'
>>> ' and '.join(('bangers', 'mash'))
'bangers and mash'

''只是空字符串,并且使将一整套字符串连接成一个大字符串更容易:

>>> ''.join(('5', '4', 'apple', 'pie'))
'54applepie'

在您的示例的特定情况下,语句会查找 <td> 中包含的所有文本元素,包括任何包含的 HTML 元素,例如 <b><i><a href="">并将它们全部放在一根长串中。所以td.find(text=True)找到一个 python 字符串序列,''.join()然后将它们连接成一个长字符串。

关于python - join 如何在 python beautifulsoup 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com