Python-Beautiful Soup刮板返回一些(但不是全部)文本

时间:2019-02-02 02:32:47

标签: python web-scraping beautifulsoup

我正试图从此list抢走美国排名前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)

Beautiful Soup返回我所期望的,职位被标签包围,除了它只属于“中学教师”,在100个职位中仅排名25。我在其他网页上以同样的方式使用了Beautiful Soup,没有问题。网页/我的代码是否有些时髦,导致输出不完整?

1 个答案:

答案 0 :(得分:1)

在浏览器的开发人员工具中打开“网络”选项卡时,我看到在滚动时发出了XHR请求,并且某些响应包含列表项。您仅能获得前24个项目,因为没有触发这些请求。其中一个请求的网址是:

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']