首页 > 解决方案 > 如何解决 Keyerror(return self.attrs[key]) 以在 Python 上提取数据?

问题描述

我正在尝试使用 Python 制作 web Scraper,但在提取公司名称时出现问题。

def extract_indeed_job():
jobs = []
result = requests.get(f"{url}&start={0*LIMIT}")
result_soup = BeautifulSoup(result.text, "html.parser")
results = result_soup.find_all("a", {"class": "tapItem"})
for result in results:
    title = result.find("h2", {"class": "jobTitle"}).find("span")["title"]
    company = result.find("span", {"class": "companyName"}).get_text()
    location = result.find("div", {"class": "companyLocation"}).get_text()
    print(title, company, location)

有的帖子,h2 class="jobTitle"标签里面有两个span标签 在此处输入图像描述

我只需要获得跨度标题。所以我用这个标签写了。但是,Python 注意到关键错误并且它不起作用。

我能做些什么来解决?我的代码有问题吗??

标签: pythonweb-scrapingbeautifulsoup

解决方案


True确保您正在过滤具有该属性的那些,span因此当您尝试访问其值时,您不会收到错误消息。find只是返回您需要的属性的粗心span

result.find("span", title=True)['title']

您提供的代码和 html 是模棱两可的。你的语句title = result.find("h2", {"class": "jobTitle"})永远不会匹配h2标签,因为它的类属性更复杂,`jobTitle jobTitle-color-purple jobTitle-newJob`。匹配你需要的

import re
...

result.find("h2", class_=re.compile(r'jobTitle'))

使用正则表达式来改进汤中的搜索。


推荐阅读