AttributeError:“Response”对象没有属性“txt”Python Web抓取

2024-10-16 17:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个新的项目,以摆脱我能做的最基本的事情,我决定研究网页抓取。 我的想法是使用SteamStatus检查Steam的当前状态,并让我的脚本打印它。对于第一个,我使用了蒸汽商店的状态,并编写了以下代码:

import requests
import bs4

res = requests.get('https://www.steamstatus.io/')
res.raise_for_status

SteamStatus = bs4.BeautifulSoup(res.txt, 'html.parser')
type(SteamStatus)

storeStatus = SteamStatus.select('#statustables > div.statustable.left > div > div:nth-child(1) > div.statusrow_status.store-status')
print(str(storeStatus))

这样,我得到了以下错误:

Traceback (most recent call last):
  File "C:/Users/a864/PycharmProjects/automation/steam status/webpage.py", line 8, in <module>
    SteamStatus = bs4.BeautifulSoup(res.txt, 'html.parser')
AttributeError: 'Response' object has no attribute 'txt'

根据我的搜索和发现,这可能是请求模块的过时版本的问题,但我已经确定我有最新版本(2.24.0)


Tags: 项目import版本divtxtparser状态html
2条回答

欢迎来到SO

如前面的回答所述,错误与使用错误的属性.txt有关,尽管.text正确

最后要注意的是,您试图刮取的页面加载了javascript,因此requests不是您要寻找的包。有关使用seleniumwebdriver的大致解决方案,请参见下文

from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Firefox() # initialize the driver

driver.get('https://www.steamstatus.io/') # go to the page

source = driver.page_source # extract the source

SteamPage = BeautifulSoup(source, 'html.parser')

SteamStatus = SteamPage.findAll('div', {'class' : 'statusrow'})
for s in SteamStatus:
    print(s.findNext('div', {'class' : 'statusrow_name'}).text) # print the row name
    print(s.findNext('div', {'class' : 'statusrow_status'}).text) # and the uploaded value

正如异常告诉您的,您正试图引用一个不存在的属性。Response公开的是.text属性,而不是.txt属性

相关问题 更多 >