【问题标题】:need to extract information in html elements using python an print it需要使用python提取html元素中的信息并打印它
【发布时间】:2019-09-10 08:04:16
【问题描述】:

我希望在 html 中的 div 标记或类元素中提取信息并在 python 中打印输出。

我想在html代码中打印“xyz”。

<div data="xyz" data-index="3" class="sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-12-of-16 sg-col-24-of-28" data-cel-widget="search_result_3"><div class="sg-col-inner">

Python 代码

soup = BeautifulSoup(r.content, 'html.parser')

data_class = soup.find_all("div", {"class": "sg-col-20-of-24 s-result-item sg-col-0-of-12 sg-col-28-of-32 sg-col-12-of-16 sg-col-24-of-28"})

for data1 in data_class:

    print(data1.get('data'))

【问题讨论】:

  • 你当前的代码发生了什么?有问题吗?
  • AttributeError:ResultSet 对象没有属性“get”。您可能将项目列表视为单个项目。当你打算调用 find() 时,你调用了 find_all() 吗?

标签: python html beautifulsoup python-requests


【解决方案1】:

您的“类”属性由多个类组成。如果您需要按多个类进行过滤,bs4 期望它们在一个列表中,而不是一个由空格分隔的类的单个字符串。 当然,只对所有类做类似data_class = soup.find_all("div", {"class": ["sg-col-20-of-24", "s-result-item"]}) 的操作,而不仅仅是作为示例添加的那些

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2019-11-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多