【问题标题】:BeautifulSoup returns empty span elements?BeautifulSoup 返回空跨度元素?
【发布时间】:2019-06-13 15:59:33
【问题描述】:

我正在尝试从 Binance 的主页获取价格,BeautifulSoup 为我返回空元素。 Binance 的主页位于https://www.binance.com/en/,我试图从中获取文本的有趣块是:

<div class="sc-62mpio-0-sc-iAyFgw iQwJlO" color="#999"><span>"/" "$" "35.49"</span></div>

Binance 的主页上有一个表格,其中一列的标题是“最后价格”。最后一个价格旁边是最后一个淡灰色的美元价格,我正试图拉出每一个。到目前为止,这是我的代码。

def grabPrices():
    page = requests.get("https://www.binance.com/en")
    soup = BeautifulSoup(page.text, "lxml")

    prices = soup.find_all("span", {"class": None})
    print(prices)

但输出只是一大堆“-”标签。

【问题讨论】:

  • 网站使用 AJAX 将所有破折号替换为当前值。 BS 不运行 JavaScript。

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

Selenium 应该是从这个 biniance 页面抓取您想要的表格内容的一种方式。和 google 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

最终输出如下:

【讨论】:

  • 谢谢,我在 BeautifulSoup 中使用了 selenium,因为我无法定义 Selector 类,但它确实有效!
  • 很高兴它有效。不过,我刚刚更新了我的答案以完成此方法,请随意采用任何有用的方法。无法定义选择器的一个可能原因可能是因为如果您一次性运行我以前的代码(除了在 jupyter notebook 中逐步执行之外),代码的处理速度比加载 Web 的速度快,因此选择器找不到页面源内容。解决方案是在代码中添加 time.sleep() 以便在处理之前有时间让页面加载(我也更新了该部分)。
猜你喜欢
  • 2020-08-28
  • 2010-10-17
  • 2020-10-13
  • 2021-07-17
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
相关资源
最近更新 更多