使用Python抓取HTML中双引号内字符串出现TypeError如何解决
报错原因
re.findall()仅接受字符串或字节类型的输入参数,soup.find_all("td")返回的是BeautifulSoup的Tag对象,直接传入会触发类型不匹配错误。- 原代码没有筛选高亮区域的内容,会抓取所有td标签下的双引号内容,不符合需求。
修正后可运行代码
from selenium import webdriver from bs4 import BeautifulSoup import re driver = webdriver.Chrome(executable_path=r"C:\Users\sandheep\OneDrive\desktop\chromedriver.exe") driver.get("https://www.emojimeanings.net/list-smileys-people-whatsapp") content = driver.page_source soup = BeautifulSoup(content, "lxml") # 筛选高亮区域的td标签,此处以该站高亮td通用class属性为例,可根据实际页面结构调整筛选规则 for td_item in soup.find_all("td", class_="highlight"): # 提取标签内的文本内容再传入正则匹配 result = re.findall(r'"([^"]*)"', td_item.text) if result: for quote_str in result: print(quote_str) driver.quit()
核心修改点
- 调用
td_item.text获取标签内的纯文本内容,解决参数类型不匹配的报错 - 给
find_all方法增加class_="highlight"过滤条件,仅匹配高亮区域的内容 - 增加空结果判断,过滤无匹配的无效输出
- 补充
driver.quit()主动关闭浏览器进程,避免后台残留冗余进程
内容的提问来源于stack exchange,提问作者Sandheep Kumar Patro
相关产品推荐
相关产品推荐

