python - 属性错误: 'Response' object has no attribute 'txt' - Python Web Scraping

标签 python web-scraping beautifulsoup python-requests

我正在开发一个新项目,以摆脱我能做的最基本的事情,我决定研究网络抓取。 我的想法是使用 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)

最佳答案

欢迎来到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

关于python - 属性错误: 'Response' object has no attribute 'txt' - Python Web Scraping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62666613/

相关文章:

python - 如何为python代码文件创建我们自己的linux命令

python - 如何向初学者解释 int() 函数

Python,BeautifulSoup 寻找 HTML 片段

python-3.x - 为什么我得到 "UnicodeEncodeError: ' charmap' 编解码器无法在位置 84811 : character maps to <undefined>"error? 编码字符 '\u25b2'

python - 如何在python中抓取网页上id = "firstheading"之后的所有信息?

python - 从 Python 运行 SQL 'Kill'

python - 整数字段前缀零不显示

javascript - 如何在javascript中的promise之后返回值

python - "TypeError: object of type ' 响应 ' has no len()"

python - 如何在 Python 中自动填写表单数据、提交表单并下载响应 ZIP 文件