【发布时间】:2021-10-08 23:24:12
【问题描述】:
免责声明 -- 我是 python 新手!
对于我的第一个项目,我正在学习使用 bs4 抓取 Indeed.com 招聘数据。我要提取的数据是职位,它位于两个不同 h2 的跨度中(因为似乎“新”职位的职位与其他职位的分类不同)。
源数据来自这个url:https://uk.indeed.com/jobs?q=devops&l=United+Kingdom&start=0
这是我的代码:
import requests
from bs4 import BeautifulSoup
#extract
def extract(page):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'}
url = f'https://uk.indeed.com/jobs?q=devops&l=United+Kingdom&start={page}'
r = requests.get(url, headers)
soup = BeautifulSoup(r.content, 'html.parser')
return soup
#transform
def transform(soup):
title1 = soup.find_all('h2', class_ = 'jobTitle jobTitle-color-purple')
title2 = soup.find_all('h2', class_ = 'new topLeft')
for item in title1:
title = item.find('span').text
print(title)
for item in title2:
title = item.find('span').text
print(title)
c = extract(0)
transform(c)
虽然我的代码运行良好,但我的问题是:我是否可以重写这段代码,所以我只有一个 for 循环来检查 title1 和 title2 的数据?我想学习良好的编码实践,因此非常感谢任何帮助重构它!
【问题讨论】:
标签: python html web-scraping beautifulsoup