【问题标题】:How does join work in python beautifulsoup在 python beautifulsoup 中加入如何工作
【发布时间】:2012-09-05 13:48:45
【问题描述】:

我正在学习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?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

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

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

    '' 只是一个空字符串,可以更轻松地将一整组字符串组合成一个大字符串:

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

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

    【讨论】:

    • @martijin - 感谢您的解释,我想我现在明白了!
    • 完成!我无法标记答案,因为 SO 对低代表的人施加了时间延迟:D 无论如何,再次感谢!
    【解决方案2】:

    Join 不是 BeautifulSoup 的一部分,而是 Python 中字符串的内置方法。它将一系列元素与给定的字符串连接在一起;例如,'+'.join(['a', 'b', 'c'])a+b+c。见the documentation

    【讨论】:

      【解决方案3】:

      代码不正确。这一行:

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

      使用 find,它返回 td 标记的第一个字符串子项并尝试对其使用 join。它可以正常工作,因为 ''.join() 只是迭代第一个字符串子项,创建一个副本。

      所以:

      <td>foo<b>bar</b></td>
      

      只需运行 ''.join("foo")。

      改为使用 td.text 属性。它会自动查找 td 中的所有字符串并将它们连接起来。

      text = td.text
      

      【讨论】:

        猜你喜欢
        • 2017-05-06
        • 2019-02-17
        • 2020-11-21
        • 2016-12-14
        • 2020-11-18
        • 2021-12-03
        • 2018-11-27
        • 2016-05-27
        • 1970-01-01
        相关资源
        最近更新 更多