python - 使用 Selenium 和 Beautifulsoup 进行 Python 抓取无法提取嵌套标签,错误对象不可调用
问题描述
我无法使用 find_next、find_children 或 find_next_siblings 提取嵌套标签,导致 TypeError: can only concatenate str(not"Tag") to str or object is not callable,有什么方法可以提取嵌套标签?谢谢你。
解决方案
BeautifulSoup 文档find_children
中没有这样的方法,这就是您收到错误的原因。但是,考虑到这是一个固定的网页 html 并且不会很快改变,您可以使用而不是依赖循环来提取 weight 和 weight_scale 。object is not callable
contents[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)
如果您还想尝试其他方法,可以查看我之前链接的文档。
推荐阅读
- javascript - 制作一个简单的全局私有变量 - 访问正文元素
- python-3.x - 如何在我用 PyQt5 制作的 GUI 中显示来自 psql 数据库的数据?
- java - 如何正确地将许多服务注入 Spring MVC 控制器?
- c++ - 结构和向量的 C++ 奇怪行为
- sql-server - 在将平面文件导入 SQL Server 表时插入日期
- javascript - 通过javascript将按钮元素更新为倒数计时器
- python - Webots 上的 Python 交互式终端?
- linux - 如何使用 sed 删除度数符号(M-0 又名上标零?)
- javascript - localstorage observable 服务上的主题切换器
- c++ - Cpp switch 语句不会输出条件集