python - 网页抓取 : Xpath list index out range

标签 python list xpath web-scraping

当我运行以下代码时,我收到列表索引超出范围消息:

import requests
from lxml.html import fromstring

def get_values():
    print('executing get_values...')
    url = 'https://sports.yahoo.com/nba/stats/weekly/?sortStatId=POINTS_PER_GAME&selectedTable=0'
    response = requests.get(url)
    parser = fromstring(response.text)
    for i in parser.xpath('//tbody/tr')[:100]:
         **FGM = i.xpath('.//td[4]/span/text()')[0] #This runs with no error even though its has similar xpath.**
         print('FGM: ' + FGM)     
         G = i.xpath('.//td[2]/span/text()')[0]
         print(G)

values = get_values()

当我运行代码时,我收到以下错误消息:

 G=i.xpath('/./td[2]/span/text()')[0]
 IndexError: list index out of range

我尝试使用以下语句进行调试。

print(parser.xpath('//tbody/tr/td[2]/span/text()')) #Returns list['4', '4', '3', '3', '3', '4', '4', '3', '2', '4', '3']
print(parser.xpath('//tbody/tr/td[2]/span/text()')[0]) #Returns value = 4
print(len(parser.xpath('//tbody/tr/td[2]/span/text()')[0])) # Returns value = 1

输出显示了预期值,因此我不确定它不起作用的原因。任何帮助将不胜感激!

最佳答案

它失败了,因为并不总是有 <span>在第二个<td> 。这应该有效:

def get_values():
    print('executing get_values...')
    url = 'https://sports.yahoo.com/nba/stats/weekly/?sortStatId=POINTS_PER_GAME&selectedTable=0'
    response = requests.get(url)
    parser = fromstring(response.text)
    for i in parser.xpath('//tbody/tr')[:100]:
         FGM = i.xpath('.//td[4]/span/text()')[0] #This runs with no error even though its has similar xpath.**
         print('FGM: ' + FGM)
         G = i.xpath('.//td[2]/text()|.//td[2]/span/text()')[0]  # <--- Changed this
         print(G)

values = get_values()

关于python - 网页抓取 : Xpath list index out range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141642/

相关文章:

python - 如何更改 `aiohttp` 请求中的 SSL 版本?

python - 使用 rpy2 和 ggplot2 制作图表

selenium - Xpath 有效,可以在 Elements 和 Console 中找到,但在运行应用程序时找不到

python - 一个简单的网络爬虫的问题

XPath 用于在 OnClick 中定位带有特定文本的 <TD> 标记

python - 验证时间序列中的时间戳

python - 如何在 Python 中测试一个数字是否为平方数?

java - 将列表的元素复制到二维数组

python - 过滤列表中与每行 pandas 的条件匹配的第一个元素

c++ - 对指针列表进行排序 C++ - 没有匹配的函数错误