首页 > 解决方案 > 使用 Selenium 和 Beautifulsoup 进行 Python 抓取无法提取嵌套标签,错误对象不可调用

问题描述

我无法使用 find_next、find_children 或 find_next_siblings 提取嵌套标签,导致 TypeError: can only concatenate str(not"Tag") to str or object is not callable,有什么方法可以提取嵌套标签?谢谢你。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

标签: pythonseleniumweb-scrapingbeautifulsoup

解决方案


BeautifulSoup 文档find_children中没有这样的方法,这就是您收到错误的原因。但是,考虑到这是一个固定的网页 html 并且不会很快改变,您可以使用而不是依赖循环来提取 weight 和 weight_scale 。object is not callablecontents[0]

请注意,我选择使用该requests库向网页发出请求并获取 HTML,但您可以尝试使用 PhantomJS 运行您的代码。

import requests
from bs4 import BeautifulSoup

page = requests.get("https://stats.nba.com/player/1629121/")
soup = BeautifulSoup(page.content, 'html.parser')

height_div = soup.find('div', string='HT')
height = height_div.find_next().contents[0]

weight_div = soup.find('div', string='WT')
weight = weight_div.find_next().contents[0].strip()
weight_scale = weight_div.find_next().contents[1].contents[0]

age_div = soup.find('div', string='AGE')
age = age_div.find_next().contents[0]

print(height)
print(f"{weight} {weight_scale}")
print(age)

如果您还想尝试其他方法,可以查看我之前链接的文档。


推荐阅读