【问题标题】:Problem with parser (IndexError: list index out of range)解析器问题(IndexError:列表索引超出范围)
【发布时间】:2020-04-23 09:48:21
【问题描述】:

请帮我解决这个错误:

Traceback (most recent call last):
  File "D:/Python/parser.py", line 14, in <module>
    for i in title[0].text:
IndexError: list index out of range  

代码:

import requests
from bs4 import BeautifulSoup as BS

max_page = 6

pages = []

for x in range(1, max_page + 1):
    pages.append( requests.get("https://stopgame.ru/review/new/stopchoice/p" +  str(x) )  )
for r in  pages:
    html = BS(r.content, "html.parser")

    for el in html.select(".lent-block"):
        title = el.select(".lent-block > a")
        for i in title[0].text:
         title.text[0](title)

【问题讨论】:

  • 那说明你的标题列表是空的,为什么不检查title的内容
  • 欢迎来到 SO! title = el.select(".lent-block &gt; a") 返回一个空列表,因此 [][0] 超出范围。你的预期输出是什么?您是否尝试获取标题文本?

标签: python beautifulsoup


【解决方案1】:

我通过您的变量名称假设您想要获得每个游戏的标题。如果是这样,您可以直接定位.lent-title &gt; a.lent-block &gt; a 给你一个空列表,因为&gt; 指定一个直接的孩子,而不是任何后代。 lent-block a 会给你所有的后代。

import requests
from bs4 import BeautifulSoup

max_page = 6

for i in range(max_page):
    page = requests.get(f"https://stopgame.ru/review/new/stopchoice/p{i + 1}")
    html = BeautifulSoup(page.content, "html.parser")

    for el in html.select(".lent-title > a"):
        print(el.text)

输出:

Disco Elysium: Обзор
Dragon Quest XI S: Echoes of an Elusive Age - Definitive Edition: Обзор
Outer Wilds: Обзор
Baba Is You: Обзор
Apex Legends: Обзор
Mario & Luigi: Bowser's Inside Story + Bowser Jr.'s Journey: Обзор
Protocol: Обзор
Dead Cells: Обзор
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多