You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何抓取网页特定元素文本值?无法提取职位位置数据求助

问题解决:提取职位位置数据

问题分析

你当前的代码直接提取job-details容器的全部文本,导致日期、薪资、位置信息混在一起无法拆分。实际上job-details内部包含多个独立子元素(如<span>)分别对应这三类信息,只需针对性提取子元素即可分离位置数据。

代码修改方案

1. 修复URL格式化问题

原代码中URL的{page}未被实际替换,导致请求的页面内容重复,需改为格式化字符串实现页码替换。

2. 拆分job-details中的信息

通过获取job-details下的子元素,分别提取日期、薪资、位置:

修改后的完整代码:

from bs4 import BeautifulSoup
import requests
import pandas as pd

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36' 
           '(KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}

postList = []

def getPosts(page):
    # 用f-string格式化URL,替换页码变量
    url = f'https://www.technojobs.co.uk/search.phtml?page={page}&row_offset=10&keywords=data%20analyst&salary=0&jobtype=all&postedwithin=all'
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')

    posts = soup.find_all('div', {'class': 'jobbox'})

    for item in posts:
        # 先获取job-details容器
        job_details = item.find('div', {'class': 'job-details'})
        # 提取容器内的所有子元素(通常是span标签)
        detail_items = job_details.find_all('span')
        
        post = {
            'title': item.find('div', {'class': 'job-ti'}).text.strip(),
            # 根据子元素索引提取对应信息,若页面结构不同可调整索引
            'date_posted': detail_items[0].text.strip() if len(detail_items) >= 1 else '',
            'salary': detail_items[1].text.strip() if len(detail_items) >= 2 else '',
            'location': detail_items[2].text.strip() if len(detail_items) >= 3 else '',
            'description': item.find('div', {'class': 'job-body'}).text.strip()
        }
        postList.append(post)

for x in range(1, 37):
     getPosts(x)
    
df = pd.DataFrame(postList)
df.to_csv('TechnoJobs.csv', index=False, encoding='utf-8')

补充说明

  • 若页面中job-details的子元素不是<span>,或索引顺序不符,可通过浏览器开发者工具查看页面结构,调整提取逻辑(比如根据子元素的特定类名定位)。
  • 添加.strip()去除文本前后空白字符,让导出的数据更整洁。

内容的提问来源于stack exchange,提问作者Edward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:10:31