【问题标题】:Python LXML Getting Data from Steam Bundle Page - List out of the index errorPython LXML 从 Steam Bundle 页面获取数据 - 列出索引错误
【发布时间】:2021-05-19 13:37:26
【问题描述】:

我正在开发 python 程序,它在获得 steam 包的 ID 后 - 它返回 当前价格

程序正在使用 requestslxml

最终价格有两种路径:

  1. /html/body/div[1]/div[7]/div[4]/div[1]/div[2]/div/div[2]/div[10]/div[3]/ div
  2. //*[@id="game_area_purchase"]/div/div/div/div[1]/div/div/div[2]

使用示例:https://store.steampowered.com/bundle/16140

这是一个代码:

import requests
import lxml.html
    
#example URL for steam bundle    
URL = "https://store.steampowered.com/bundle/16140"
    
html = requests.get(URL)
doc = lxml.html.fromstring(html.content)
    
#xpath to price location    
price = doc.xpath('/html/body/div[1]/div[7]/div[4]/div[1]/div[2]/div/div[2]/div[10]/div[3]/div/text()')
    
print(price)

程序返回这个:

[]

或者这个

Traceback (most recent call last):
  File <path-to-program>, line 9, in <module>
    price = doc.xpath('/html/body/div[1]/div[7]/div[4]/div[1]/div[2]/div/div[2]/div[10]/div[3]/div/text()')[0]
IndexError: list index out of range

这两个选项都有错误。 我该怎么做才能解决它?

【问题讨论】:

  • 当您请求页面 requests 时,返回的结果并非您所期望的 - 它返回带有色情内容/裸露警告的页面。您可以尝试创建requests.Session 以在单个会话中发送多个请求。请注意,您应该发送带有出生日期数据的 POST 请求。另请注意,您的方法应该适用于不需要年龄验证的其他页面

标签: python xpath python-requests lxml steam


【解决方案1】:

要获得所需的页面 HTML,您需要添加带有 birthtime cookie 的请求,该 cookie “告诉”服务器您的年龄允许您访问包含性/裸露内容的页面:

import requests
import lxml.html
    
URL = "https://store.steampowered.com/bundle/16140"
session = requests.Session()
r1 = session.get(URL)
r1.cookies['birthtime']='439423201'  # this is date in seconds since "epoch" (January 1, 1970)
r2 = session.get(URL, cookies=r1.cookies)

doc = lxml.html.fromstring(r2.content)
print(doc.xpath('//div[contains(@class, "discount_final_price")]/text()')[0])

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2020-05-14
    • 2022-06-29
    相关资源
    最近更新 更多