简体   繁体   English

在BS4中获取'列表'对象没有属性错误

[英]Getting `list` object no attribute error in BS4

I am new to bs4 and am trying to experiment by building a price bot for Crypto currencies. 我是bs4 ,正在尝试通过为加密货币构建价格机器人来进行实验。 This is the code I have so far: 这是我到目前为止的代码:

import requests
import bs4
import csv
from datetime import datetime

def remove_all_whitespace(x):
    try:
        x = x.replace(" ", "")
    except:
        pass
    return x

def trim_the_ends(x):
    try:
        x = x.strip(' \t\n\r')
    except:
        pass
    return x

def remove_unneeded_chars(x):
    try:
        x = x.replace("$", "").replace("RRP", "")
    except:
        pass
    return x

URL = ("https://coinmarketcap.com/assets/golem-network-tokens/")

response = requests.get(URL)

soup = bs4.BeautifulSoup(response.text)

price = soup.select("span#quote_price.text-large").get_text()

print (price)

But I am getting this error: 但我收到此错误:

AttributeError: 'list' object has no attribute 'get_text'

What am I doing wrong? 我究竟做错了什么? From my understanding the .select does not work with list items, but how am I pulling a list ? 据我了解, .select不适用于list项,但是我如何提取list

Yes, soup.select() returns a list of matches; 是的, soup.select() 返回匹配列表 the selector can match 0 or more times. 选择器可以匹配0次或多次。

If you wanted to retrieve just one match, use the soup.select_one() method, which returns the first match, or None if there are no matches: 如果您只想检索一个匹配项,请使用soup.select_one()方法,该方法将返回第一个匹配项;如果没有匹配项,则返回None

price = soup.select_one("span#quote_price.text-large").get_text()

However, the page you loaded doesn't contain that information . 但是,您加载的页面不包含该信息 The page instead uses Javascript to load data over AJAX. 该页面改为使用Javascript通过AJAX加载数据。 requests is not a browser and won't load external resources or execute Javascript code. requests不是浏览器,也不会加载外部资源或执行Javascript代码。

The page loads the prices from https://graphs.coinmarketcap.com/currencies/golem-network-tokens/ , load that instead: 该页面从https://graphs.coinmarketcap.com/currencies/golem-network-tokens/加载价格,而不是加载:

>>> import requests
>>> r = requests.get('https://graphs.coinmarketcap.com/currencies/golem-network-tokens/')
>>> data = r.json()
>>> data['price_usd'][-1][1]
0.309104

The first element of each entry in that list is a timestamp in microseconds: 该列表中每个条目的第一个元素是一个以微秒为单位的时间戳:

>>> from datetime import datetime
>>> datetime.fromtimestamp(data['price_usd'][-1][0] / 1000)
datetime.datetime(2017, 8, 29, 18, 34, 46)

You should probably use their published API instead however: 但是,您可能应该使用其发布的API

https://api.coinmarketcap.com/v1/ticker/golem-network-tokens/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM