【问题标题】:Assign Extracted text from HTML table to Variable for later use -- Beautiful Soup / Python 3.7将从 HTML 表中提取的文本分配给变量以供以后使用——Beautiful Soup / Python 3.7
【发布时间】:2020-11-18 20:52:21
【问题描述】:

下面的代码可以完美地在 HTML 表格源代码中动态搜索特定文本并拉取找到特定文本的行的 nextSibling。

当前代码

r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
           
# Find xxxxxxx (row-by-row) and split trailing zeros
row = soup.find_all('td', string="xxxxxxx")
for r in row:
        LE = r.nextSibling
        while LE.name != 'td' and LE is not None:
                LE = LE.nextSibling

我遇到的主要问题(这可能非常简单,而且我现在已经盯着这个问题很久了)是我需要将 nextSibling 分配给 LE 变量。

LE 被格式化为“001234”,我需要去掉前导零以将“1234”作为变量。

如果我将变量打印为print(LE.text[2:6]),则结果是正确的。实现到代码中, LE = LE.nextSibling.text[2:6] 不会产生任何东西。

我尝试了以下语句,但没有任何效果,希望得到指导。

LE = LE.nextSibling.text[2:6]
&
LE = LE.text[2:6]

我需要在提取后将其分配给一个变量,以便稍后在我的脚本中使用该变量。 提前感谢您的帮助!

EDIT --> 包含源代码:

<tr>
     <td class='label' nowrap title="xxxxxxx">TEXT TO FIND</td>
     <td class='attribute'>001234</td>
</tr>

【问题讨论】:

  • 请分享网址
  • @MendelG -- 我只能提供源代码,因为您无法进入该网站,因为它是基于服务器的。如果您需要更多信息,请告诉我。

标签: python python-3.x beautifulsoup python-3.7 nextsibling


【解决方案1】:

您可以使用next_sibling 两次,然后使用strip() 删除0

from bs4 import BeautifulSoup

html = """<tr>
     <td class='label' nowrap title="xxxx">TEXT TO FIND</td>
     <td class='attribute'>001234</td>
</tr>"""

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

for tag in soup.select(".label"):
    le = ''.join([t.strip("0") for t in tag.next_sibling.next_sibling])
    print(tag.text)
    print(le)

输出:

TEXT TO FIND
1234

【讨论】:

  • 感谢帮助,但我相信我找到了问题(愚蠢的错误)——我会发布它。如果我最终遇到问题,我会再次伸出援手!
【解决方案2】:

变化:

!===

 row = soup.find_all('td', string="xxxxxx")
            for r in row:
                LE = r.nextSibling
                    LE = LE.text[2:6]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多