首页 > 解决方案 > 进一步抓取链接

问题描述

我目前正在尝试抓取https://rl.insider.gg/en/xbox并尝试识别页面上的“趋势”项目

我以某种方式达到了我拥有链接的地步,但无法弄清楚如何进一步解析它们。我想要并且想要从中提取最后一部分并将这两个值存储在两个变量中:颜色和项目

例如:(我现在拥有的链接示例)

/en/xbox/octane/white

我想去掉 en 和 xbox 位,只留下octane/white. 然后,将 存储octane为名为 item 的变量,并将 存储为white名为 color 的变量

到目前为止我所拥有的

import requests 
from bs4 import BeautifulSoup 

page = requests.get("https://rl.insider.gg/en/xbox")
soup = BeautifulSoup(page.content, 'html.parser')

trendingitems = soup.find(id="trendingItems")
for link in trendingitems.find_all('a'):
  linkitems = (link.get('href'))
  print(linkitems)

标签: pythonweb-scrapingbeautifulsoup

解决方案


尝试这个

import requests 
from bs4 import BeautifulSoup 

page = requests.get("https://rl.insider.gg/en/xbox")
soup = BeautifulSoup(page.content, 'html.parser')

trending_items = soup.find(id="trendingItems")
for link in trending_items.find_all('a'):
    link_items = link.get('href').replace('/en/xbox/', '')
    split_items = link_items.split('/')
    if len(split_items) == 2:
        item = split_items[0]
        colour = split_items[1]

我计算 split_items 因为一些返回值没有颜色。如果我得到 2 的结果,我们就知道我们已经有了商品和颜色。

octane/white
zomba/white
fennec
fennec/white
dissolver
mainframe
interstellar
octane/crimson
dueling_dragons
standard/black
emerald/white
mainframe/white
octane/sblue
big_splash
octane/lime
stipple_gait
emerald/black
helios/white
interstellar/white
standard/white
20xx
dieci_uncommon/black
fire_god
heatwave
zomba

推荐阅读