【问题标题】:AttributeError: 'Response' object has no attribute 'txt' - Python Web ScrapingAttributeError:“响应”对象没有属性“txt” - Python Web Scraping
【发布时间】:2020-06-30 21:46:32
【问题描述】:

我正在开发一个新项目,以摆脱我能做的最基本的事情,我决定研究网络抓取。 我的想法是使用SteamStatus 检查 Steam 的当前状态并让我的脚本打印出来。对于第一个,我使用 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)

【问题讨论】:

  • 不,因为它的意思是.text,而不是.txt ...

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

欢迎来到 SO!

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

最后一点,您尝试抓取的页面是用 javascript 加载的,因此 requests 不是您要查找的包。使用selenium webdriver 的粗略解决方案见下文

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 最终解决了这个问题,谢谢。 [&lt;div class="statusrow_status store-status"&gt;Loading&lt;/div&gt;] 现在我的问题是这是我得到的输出。 “加载”实际上应该是“正常”、“延迟”等,我知道当网站加载时,会出现“加载”,有什么办法可以让它在完全加载后才刮掉?我已经尝试过time.sleep,但持续了 20 秒(比我加载所需的时间要长),但它仍然显示“正在加载”
    • @Meirewes 如果您有单独的问题,请提出单独的问题...您可能需要考虑该状态是否是由 javascript 生成的...
    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 2022-11-14
    • 2022-07-22
    • 2014-04-20
    • 1970-01-01
    • 2016-05-15
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多