我试图从币安主页获取价格,BeautifulSoup 为我返回空元素。币安的主页是https://www.binance.com/en/ ,我试图从中获取文本的有趣 block 是:
<div class="sc-62mpio-0-sc-iAyFgw iQwJlO" color="#999"><span>"/" "$" "35.49"</span></div>
币安的主页上有一个表格,其中一栏的标题是“最新价格”。最后一个价格旁边是最后一个美元价格,呈褪色灰色,我正在尝试提取其中的每一个。这是到目前为止我的代码。
def grabPrices():
page = requests.get("https://www.binance.com/en")
soup = BeautifulSoup(page.text, "lxml")
prices = soup.find_all("span", {"class": None})
print(prices)
但是输出只是一大堆“-”标签。
最佳答案
Selenium 应该是从这个 biniance 页面中抓取您想要的表格内容的一种方法。并谷歌 Selenium 了解其设置(几乎通过下载驱动程序并将其放置在本地磁盘中,如果您是 chrome 用户,请参阅此下载链接 chrome driver )。这是我访问您感兴趣的内容的代码:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
driver = webdriver.Chrome(executable_path=r'C:\chromedriver\chromedriver.exe')
time.sleep(3) # Allow time to launch the controlled web
driver.get('https://www.binance.com/en/')
time.sleep(3) # Allow time to load the page
sel = Selector(text=driver.page_source)
Table = sel.xpath('//*[@id="__next"]/div/main/div[4]/div/div[2]/div/div[2]/div/div[2]/div')
Table.extract() # This basically gives you all the content of the table, see follow screen shot (screen shot is truncated for display purpose)
然后,如果您使用以下内容进一步处理整个表格内容:
tb_rows = Table.xpath('.//div/a//div//div//span/text()').extract()
tb_rows # Then you will get follow screen shot
此时,结果已缩小到您感兴趣的范围,但请注意,lastprice 的两个组成部分(数字/美元价格)存储在源页面中的两个标签中,因此我们可以执行以下操作来组合它们一起到达目的地:
for n in range(0,len(tb_rows),2):
LastPrice = tb_rows[n] + tb_rows[n+1]
print(LastPrice) # For sure, other than print, you could store each element in a list
driver.quit() # don't forget to quit driver by the end
最终输出如下:
关于python - BeautifulSoup 返回空的 span 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584436/