【问题标题】:Finding a span tag with a 'variable'? but no class - Beautiful soup/Python找到带有“变量”的跨度标签?但没有课 - 美丽的汤/Python
【发布时间】:2021-07-25 13:22:24
【问题描述】:

我正在使用 BeautifulSoup 和 Python 来查找似乎没有类的 span 标签。

我想在 span 标签中获取文本“1hr ago”,它有一个...变量?名为“data-automation”,但我似乎不知道如何使用漂亮的汤来找到它。

第一个跨度有一个“_3mgsa7- _2CsjSEq _2gpxOIH _15GBVuT _3VdCwhL _2Ryjovs”类,它使用我的代码生成文本,但也有错误。

谁能帮我修复错误或解释如何找到“数据自动化”跨度标签?

我的密码:

joblist =soup.find_all('article', class_='_37iADb_ _3BsYYYt')
for job in joblist:
    listed = job.find('span', class_="_3mgsa7- _2CsjSEq _2gpxOIH _15GBVuT _3VdCwhL _2Ryjovs").text
    print(f'listed {listed}')

错误:

  Traceback (most recent call last):
      File "C:\Users\User\PycharmProjects\Scraping1\ScrapeTut 2 - scraping websites.py", line 34, in <module>
        listed = job.find('span', class_="_3mgsa7- _2CsjSEq _2gpxOIH _15GBVuT _3VdCwhL _2Ryjovs").text
    AttributeError: 'NoneType' object has no attribute 'text'

网站 HTML 代码:

<span class="_3mgsa7- _2CsjSEq _2gpxOIH _15GBVuT _3VdCwhL _2Ryjovs">
  <span class="">
    <span aria-hidden="true" data-automation="jobListingDate">1h ago</span>
  </span>
</span>

【问题讨论】:

  • 您能否附上您要废弃的网站的网址?
  • 尝试打印job的类型和listed的类型与type(job)type(listed)

标签: python beautifulsoup


【解决方案1】:

您可以通过将attrs dict 作为关键字参数传递给.find().find_all() 来选择具有特定属性(例如data-automation)的&lt;span&gt; 元素。请参阅documentation

要查找&lt;span&gt;data-automation 有任何值:

soup.find('span', attrs={'data-automation': True})

其中data-automation 具有特定值:

soup.find('span', attrs={'data-automation': 'jobListingDate'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2021-06-24
    • 2017-12-05
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多