【问题标题】:Python - Beautiful Soup scraper returning some, but not all, textPython - Beautiful Soup scraper 返回一些但不是全部文本
【发布时间】:2019-02-02 02:32:46
【问题描述】:

我正在尝试从这个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 没有问题。网页/我的代码有什么奇怪的地方导致输出不完整吗?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    在浏览器的开发人员工具中打开网络选项卡后,我看到在滚动时正在发出 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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多