【问题标题】:Separating two texts within same <td> tag using Python BeautifSoup使用 Python BeautifulSoup 在同一 <td> 标记中分隔两个文本
【发布时间】:2016-10-28 02:33:45
【问题描述】:

我的 HTML 知识非常有限,而且我才刚刚开始研究 Beautiful soup,所以我的问题可能没有正确表达。 我的 HTML 源代码看起来像这样

<TD width="15%">Text1</TD>
<TD width="85%">Text2<A href="link1">(6)</A> 
Text3<A href="link2">(4)</A> 
</TD>

它在网页上显示为 Text1/Text2 和 Text1/Tex3(可能是由于一些我不理解的代码,我可能没有在此处复制)。

但是,我正在尝试使用 BeautifulSoup 编写 Python 代码来解析 Python 对象中的这些信息。我认为第一步只是分别提取文本,然后再合并它们。我可以使用这样的代码轻松提取 Text1

url = "my url (static page stored locally)"
soup = BeautifulSoup(open(url),'lxml')
t1_soup=soup.find_all('td',{'width':'15%'})
t2_soup=soup.find_all('td',{'width':'75%'})


text1_str=[]
for item in t1_soup:
text1_str.append(item.text)


text2_str=[]
for item in t2_soup:
text2_str.append(item.text)

第一个 for 循环清晰地给了我 text1,但第二个 for 循环给了我一个字符串'text2 text3'。我不确定如何将它们分开,以便最终将其转换为 text1/text2 和 text1/text3

我编写的 python 代码也可能效率不高,如果您有更好的解决方法的建议,我将不胜感激。

【问题讨论】:

    标签: python html parsing beautifulsoup


    【解决方案1】:

    您可以通过查找td 中的所有a 元素并获取previous text siblings 来解决它:

    for item in t2_soup:
        print([a.previous_sibling.strip() for a in item.find_all("a")])
    

    打印[u'text2', u'text3']

    或者,您可以在每个td中找到所有文本节点非递归

    for item in t2_soup:
        print([text.strip() for text in item.find_all(text=True, recursive=False)])
    

    这可能会产生额外的空字符串 - 确保过滤它们。

    【讨论】:

    • 这很好用@alecxe。我自己不可能解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2022-12-29
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多