Python网页爬虫:使用bs4提取网页文本时报TypeError如何解决?
错误原因
你当前代码中的html是字符串类型,Python原生字符串的find()方法仅支持传入子串、起始/结束索引等参数,你传入"div"、属性字典两个不符合要求的参数,才会触发该类型错误。
你要调用的是BeautifulSoup提供的DOM元素查找方法,需要先把HTML字符串解析为BeautifulSoup实例后再使用。
修复后的代码
from urllib.request import urlopen from bs4 import BeautifulSoup url = "https://www.oddsshark.com/nfl/dallas-pittsburgh-odds-august-5-2021-1410371" page = urlopen(url) html_bytes = page.read() html = html_bytes.decode("utf-8") # 将HTML字符串解析为BeautifulSoup对象 soup = BeautifulSoup(html, "html.parser") # 调用bs的find方法查找对应节点 target_node = soup.find("div", {"class":"gc-score__title"}) if target_node: # 提取节点内的文本内容 text = target_node.get_text(strip=True) print(text) else: print("未匹配到对应元素")
补充说明
若运行后仍提示未匹配到元素,是因为该站点内容为前端动态渲染,直接请求拿到的静态HTML中不包含对应节点,你可以通过添加请求头模拟浏览器访问,或使用支持动态页面渲染的工具爬取。
内容的提问来源于stack exchange,提问作者gasper101
相关产品推荐
相关产品推荐

