【问题标题】:CSS Selector does not extract the data I wantCSS Selector 没有提取出我想要的数据
【发布时间】:2021-03-05 22:15:21
【问题描述】:

试图获取 MBBM 的当前股票价格,但它没有使用复制选择器(在 Chrome 上)提取它,如代码的 soup.select 部分所示:

导入 bs4,请求

股票代码 = MBBM URL = 'https://www.bursamarketplace.com/mkt/themarket/stock/' + 股票代码

def getStockPrice(URL): res = requests.get(URL) res.raise_for_status

soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('body > main > div > div > div > section > div.topPnl_cnt.row > div.movemBox.small-12.medium-12.large-2.column > div:nth-child(1) > div.priceBox.small-6.medium-6.large-12.column.downBox > div.value')
return elems[0].text.strip()

价格 = getStockPrice(URL) 打印(价格)

import bs4, requests

#stockCode = input('Insert BursaMKTPLC stock code: \n')

stockCode = 'MBBM'
URL = 'https://www.bursamarketplace.com/mkt/themarket/stock/' + stockCode

res = requests.get(URL)
print(res.raise_for_status)

soup = bs4.BeautifulSoup(res.text, 'html.parser')

price = soup.find("div", {"name": "tixStockLast"}).text.strip()
print(price)

输出为无

【问题讨论】:

  • 请重新整理您的问题并提供更多信息 - 具体的 url、元素、输出将有助于理解
  • 感谢更新看起来好多了 - 输出不是,因为price element 信息是动态生成的,并且它现在不存在request.get() 获取源代码:<div class="value" name="tixStockLast"><div class="loader loaderSmall"><div class="loader_hld"><img alt="" src="/img/loading.gif"/></div></div></div> 你应该尝试@ 987654322@ 而不是 request 并使用它的等待来检测是否加载了 price

标签: python beautifulsoup


【解决方案1】:

尝试使用 Selenium

from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\Program Files\Chrome Driver\chromedriver.exe') #replace with your path to chromedriver

stockCode = 'MBBM'
URL = 'https://www.bursamarketplace.com/mkt/themarket/stock/' + stockCode

driver.get(URL)

给页面一些时间来加载动态生成的信息

driver.implicitly_wait(10) # wait for seconds

找到你的元素

elements = driver.find_element_by_name('tixStockLast')
elements.text

输出

'8.100'

【讨论】:

  • 我尝试了这个并且得到了这个错误:DevTools正在监听ws://127.0.0.1:61031/devtools/browser/428ea207-2de1-4bec-967c-5da458a73284 [6228:16304:1126/150954.088 :ERROR:device_event_log_impl.cc(211)] [15:09:54.087] 蓝牙:bluetooth_adapter_winrt.cc:1073 获取默认适配器失败。尝试过:更新了 Chrome、chromedriver 和 selenium
  • 注意为什么会出现这个错误,这个答案可能会有所帮助:stackoverflow.com/questions/61561112/…
  • 我使用 Firefox 作为我的网络驱动程序,它工作正常,谢谢你的帮助!!
猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
相关资源
最近更新 更多