【问题标题】:Beautifulsoup scrape data-slugBeautifulsoup 抓取数据块
【发布时间】:2021-03-06 12:37:15
【问题描述】:

我想从页面内容中获取 data-slug 值,如下所示:

...
<div class="my_class" data-slug="I_want_to_scrap_it" data-title="Title">
<br> Some text </div>
...

我通过 find_all(class_="my_class") 方法找到了它,但我不知道如何从中提取“I_want_to_scrap_it”。当然,我可以将其转换为字符串并获取子字符串,但也许有一个非常简单的 Beautifulsoup 方法可以做到这一点。

谢谢你,祝你有美好的一天!

【问题讨论】:

  • 这是scrape 不是 scrap...
  • 好的,谢谢。现在是刮了。
  • @MartinDomino 向我们展示您的代码不会有什么坏处。将帮助我们获取图片。

标签: python beautifulsoup screen-scraping


【解决方案1】:

这是一个例子:

html = '''<div class="my_class" data-slug="I_want_to_scrap_it" data-title="Title">
<br> Some text </div>
'''

# solution using BeautifulSoup
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html5lib')

div = soup.select('div.my_class')[0]
data_slug = div.get('data-slug')
print(data_slug)

data-slug 是一个属性,可以使用函数get() 检索。

【讨论】:

  • 谢谢亚历山德拉!
猜你喜欢
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多