来自 html 的所有元素未被请求和 Python 中的 BeautifulSoup 提取

All elements from html not being extracted by Requests and BeautifulSoup in Python

我正试图从一个显示不同机构的当前赔率的网站上获取赔率,以分配对市场竞争影响的分配。我正在使用 Requests 和 BeautifulSoup 来提取相关数据。但是使用后:

import requests
from bs4 import BeautifulSoup

url = "https://www.bestodds.com.au/odds/cricket/ICC-World-Twenty20/Sri-Lanka-v-Afghanistan_71992/"

r=requests.get(url)
Print(r.text)

它不打印任何赔率,但如果我检查页面上的元素,我可以在 html 中看到它们。我如何获得将它们导入 Python 以提取的请求?

requests 不太适合table 在这种情况下使用 - 该站点 非常动态 并使用多个 XHR 请求和 javascript 组成页面。获得所需信息的一种更快且更轻松的方法是 使用真正的浏览器 通过 selenium.

自动化

这是一个让您入门的示例代码 - 使用无头 PhantomJS 浏览器:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.PhantomJS()
driver.get("https://www.bestodds.com.au/odds/cricket/ICC-World-Twenty20/Sri-Lanka-v-Afghanistan_71992/")

# waiting for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".odds-comparison")))

for comparison in driver.find_elements_by_css_selector(".odds-comparison"):
    description = comparison.find_element_by_css_selector(".description").text
    print(description)

driver.close()

它在页面上打印所有赔率table描述:

MATCH ODDS
MOST SIXES
TOP SRI LANKA BATSMAN
TOP AFGHANISTAN BATSMAN

最好使用 urlopen :

   import urllib
   from bs4 import BeautifulSoup
   from urllib.request import urlopen

   url = "https://www.bestodds.com.au/odds/cricket/ICC-World-Twenty20/Sri-Lanka-v-Afghanistan_71992/"

   response = urlopen(url)
   htmltext = BeautifulSoup(response)
   print (htmltext)

在那之后你可以找到你想要的东西:

   Liste_page =htmltext.find('div',{"id":"pager"}).text
   Tr=htmltext.find('table',{"class":"additional_data"}).findNext('tbody').text

数据很可能动态加载

它不在 HTML。

您可以尝试了解哪些请求用于检索真实数据,或者尝试使用例如selenium webdriver 来模拟真实的浏览器(第二个选项会慢得多)。

请注意,您很可能违反了该网站的使用条款。这很容易让你陷入困境。他们也可能会故意为您提供不良数据。