从网站列表提取数据,无需多余标签

0 投票
1 回答
853 浏览
提问于 2025-04-15 17:04

有效的代码:通过Python和Beautiful Soup查找谷歌词典 -> 只需执行并输入一个单词。

我简单地从一个特定的列表项中提取了第一个定义。不过,为了得到干净的数据,我不得不在换行符处拆分我的数据,然后去掉多余的列表标签。

我的问题是,有没有什么方法可以直接提取特定列表中的数据,而不需要像我上面那样处理字符串?也许在Beautiful Soup中有我还没发现的函数?

这是相关的代码部分:

# Retrieve HTML and parse with BeautifulSoup.
    doc = userAgentSwitcher().open(queryURL).read()
    soup = BeautifulSoup(doc)

# Extract the first list item -> and encode it.
    definition = soup('li', limit=2)[0].encode('utf-8')

# Format the return as word:definition removing superfluous data.
    print word + " : " + definition.split("<br />")[0].strip("<li>")

1 个回答

1

我觉得你想要的是 findAll(text=True),这个方法可以从标签中提取文本。

definitions = soup('ul')[0].findAll(text=True)

它会返回一个列表,里面包含了所有的文本内容,按照标签的边界分开。

撰写回答