Python `beautifulsoup` 提取缺少 `class` 的 url,其他属性?

标签 python html beautifulsoup

小问题 [我对 Python 的 BeautifulSoup() 不是很熟悉] 如果我有以下元素,

如何提取/获取“1 条评论”(或“2 条评论”等)?该“a”标记中没有class(或id 或其他属性)。

<td class="subtext">
  <a href="item?id=22823679">1&nbsp;comment</a>
</td>

最佳答案

下面怎么样,用本地html文件测试

from bs4 import BeautifulSoup

url = "D:\\Temp\\example.html"

with open(url, "r") as page:
    contents = page.read()
    soup = BeautifulSoup(contents, 'html.parser')
    element = soup.select('td.subtext')
    value = element[0].get_text()
    print(value)

example.html

<html>
    <head></head>
        <body>
            <td class="subtext">
                <a href="item?id=22823679">1&nbsp;comment</a>
            </td>
        </body>
</html>

关于Python `beautifulsoup` 提取缺少 `class` 的 url,其他属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61132603/

相关文章:

Python - 函数继承 - 更改关键字参数

html - 将 CSS 样式应用于最后一个可见元素

python - 使用 Python 和 beautifulsoup4 登录网站后如何抓取搜索结果?

python - 从 HTML 标签中移除某些属性

python - 使用 pyodbc 连接到 Firebird 来绑定(bind)参数

Python——创建一棵圣诞树

python初学者: import mysite.管理失败?

javascript - 删除表行jquery

html - 无法用 2 个固定宽度的 div 包裹我的中间 100% 宽度的 div

python - 美汤-查找 child 标签属性内容