爬取Work.ua职位页面时遇AttributeError: 'NoneType'无text属性问题求助
解决爬取Work.ua职位时的
AttributeError: 'NoneType' object has no attribute 'text'错误 这个错误的核心原因是:部分职位卡片的HTML结构不完整,比如缺失薪资标签、地区节点等,导致find()方法返回None,你直接调用.text或访问属性就会触发报错。
修复方案:先检查元素存在性再访问属性
修改代码,对每个要提取的元素先判断是否存在,给缺失字段设置默认值,避免程序中断:
import requests from bs4 import BeautifulSoup url = 'https://www.work.ua/en/jobs/?ss=1' # 获取页面内容 page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') # 定位所有职位卡片 jobs = soup.find_all(class_='card card-hover card-visited wordwrap job-link js-hot-block') for job in jobs: # 提取职位标题 title_elem = job.find(class_='add-top-xs') job_title = title_elem.text.strip() if title_elem else '无职位标题' # 提取城市信息 job_city = '无城市信息' if title_elem and title_elem.next_sibling: job_city = title_elem.next_sibling.strip() # 提取薪资 salary_elem = job.find(class_='salary') job_salary = salary_elem.text.strip() if salary_elem else '无薪资标注' # 提取职位链接 link_elem = job.find('a') job_url = link_elem['href'] if link_elem else '无有效链接' print(f'Job title: {job_title}\nCity: {job_city}\nSalary: {job_salary}\nURL: {job_url}\n')
另一种方案:用异常捕获跳过不完整职位
如果不需要处理缺失字段,只想跳过有问题的职位,可以用try-except块捕获异常:
import requests from bs4 import BeautifulSoup url = 'https://www.work.ua/en/jobs/?ss=1' page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') jobs = soup.find_all(class_='card card-hover card-visited wordwrap job-link js-hot-block') for job in jobs: try: job_title = job.find(class_='add-top-xs').text.strip() job_city = job.find(class_='add-top-xs').next_sibling.strip() job_salary = job.find(class_='salary').text.strip() job_url = job.find('a')['href'] print(f'Job title: {job_title}\nCity: {job_city}\nSalary: {job_salary}\nURL: {job_url}\n') except AttributeError: print('该职位信息不完整,跳过\n') continue
内容的提问来源于stack exchange,提问作者NOLA_Max
相关产品推荐
相关产品推荐

