Python靓汤刮刀还有些,但不是全部,特克斯

2024-05-12 21:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从这本书中摘得全美前100名的工作。当我运行此代码时:

import urllib.request
from bs4 import BeautifulSoup
url = 'https://www.ranker.com/list/most-common-jobs-in-america/american-jobs'
page_opened = urllib.request.urlopen(url)

soup = BeautifulSoup(page_opened, 'html.parser')
jobs_soup = soup.find_all('span','listItem__title')
print(jobs_soup)

“靓汤”的回报和我预期的一样,职位头衔周围都是标签,只是“中学教师”的头衔只有100个职位中的25个。我在其他网页上也用过同样的方法。网页/我的代码有没有什么奇怪的地方导致输出不完整


Tags: 代码fromimporturl网页requestpagejobs
1条回答
网友
1楼 · 发布于 2024-05-12 21:41:11

在浏览器的开发工具中打开了network选项卡,我看到在滚动时发出了XHR请求,其中一些响应包含列表项。您只能获取前24项,因为这些请求未被触发。其中一个请求的url是:

https://cache-api.ranker.com/lists/354954/items?limit=20&offset=50&include=votes,wikiText,rankings,openListItemContributors&propertyFetchType=ALL&liCacheKey=null

通过将“限制”更改为100,将“偏移”更改为0,我可以获得前100个工作:

import json
from urllib.request import urlopen

# I removed the other query parameters and it still seems to work
url = 'https://cache-api.ranker.com/lists/354954/items?limit=100&offset=0'
resp = urlopen(url)
data = json.loads(resp.read())
job_titles = [item['name'] for item in data['listItems']]
print(len(job_titles))
print([job_titles[0], job_titles[-1]])

输出:

100
['Retail salespersons', 'Cleaners of vehicles and equipment']

相关问题 更多 >