【问题标题】:How can I scrape code inside div with BeautifulSoup?如何使用 BeautifulSoup 在 div 中抓取代码?
【发布时间】:2021-05-01 23:58:41
【问题描述】:

我在使用 BeautifulSoup 和 python 抓取 div 内部而不是它们之间的代码时遇到问题。下面我写了一个html代码我想抓取(data-friendscount,data-followerscount值)

<div data-profileuserid="285904056" data-friendscount="100" data-followerscount="7102" data-followingscount="25" data-arefriends="false" class="hidden ng-isolate-scope"></div>

【问题讨论】:

  • 你见过crummy.com/software/BeautifulSoup/bs4/doc/#attributes 吗?你试图获得什么价值?
  • 是的,我需要价值观
  • 你能再分享一些代码吗,你试过什么?对我来说,这些文档对如何做非常有定论。也许有一个小错字左右。上面的 HTML 是怎么处理的?
  • 我无法分享我的代码,因为它不起作用,我不知道如何在 div 中删除数据。我可以给你链接roblox.com/users/285904056/profile -- 正在尝试获取粉丝数
  • soup = BeautifulSoup(html_here) 然后 tag = soup.divtag.get(attribute_here) 作为启动器(替换 _here 部分)。

标签: python html beautifulsoup


【解决方案1】:
toc = requests.get(f'roblox.com/users/75790059/profile')
soup = BeautifulSoup(toc.content, 'html.parser')
divs = soup.find_all("div", class_="hidden ng-isolate-scope")
for div in divs:
    print(div.attrs.get('data-profileuserid', None))
    print(div.attrs.get('data-friendscount', None))
    print(div.attrs.get('data-followerscount', None))
    print(div.attrs.get('data-followingscount', None))
    print(div.attrs.get('data-arefriends', None))

【讨论】:

  • 感谢您的回复,但我无法找到带有链接的 div 也许您可以帮我找到?这是我在roblox.com/users/285904056/profile 中查看imgur.com/nhUrDwY 的照片
  • 查看我的编辑。我添加了 soup.find_all 来搜索所有具有 class= 'hidden ng-isolate-scope' 的 div。然后你可以遍历与该类名匹配的所有 div
  • 我添加了这个,但什么也没给我 `toc = requests.get(f'roblox.com/users/75790059/profile').textsoup = BeautifulSou(toc, 'html.parser')
  • 查看编辑。您应该使用 toc.content 并从 get 函数中删除 .text
  • 奇怪,但如果我搜索所有 div 我得到了它们
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2019-09-03
  • 2019-04-10
  • 1970-01-01
  • 2020-03-01
  • 2022-11-14
  • 2020-11-10
相关资源
最近更新 更多