BeautifulSoup没有得到输出

问题描述 投票:0回答:2

所以,我希望得到足球统计出表的,但首先,我想要得到的表汤。这是我有一个问题,我总是得到一个空列表。

下面是代码:

import requests
from bs4 import BeautifulSoup

url = 'https://www.eredmenyek.com/foci/nemetorszag/bundesliga/'

oldal = requests.get(url)

soup = BeautifulSoup(oldal.text, "lxml")

review_table_elem = soup.find_all('div', {'class': 'stats-table-container'})

print(review_table_elem)

和HTML代码是:

很多的div上述这里

<div class="stats-table-container"><table id="table-type-1" class="stats-table stats-main table-1" title=""> //And here is the table
python html beautifulsoup
2个回答
1
投票

一种可以替代的硒是requests-html。既然你已经熟悉的要求,您将能够轻松地拿起这件事。

from bs4 import BeautifulSoup
from requests_html import HTMLSession
import requests
session = HTMLSession()
r = session.get('https://www.eredmenyek.com/foci/nemetorszag/bundesliga/')
r.html.render(sleep=5)
soup = BeautifulSoup(r.html.html, "html.parser")
review_table_elem = soup.find_all('div', {'class': 'stats-table-container'})
print(review_table_elem)

0
投票

你和交互的页面严重依赖于JavaScript来渲染其内容。您正在寻找的数据将不会在你requests得到,因为它不评估的JavaScript响应。

要做到这一点,你需要使用的东西做,像硒的webdriver。下面是使用它和Chrome的无头实例的解决方案。除了安装selenium模块,您将需要下载ChromeDriver和更改下面的代码把它指向你提取它的位置:

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")

driver = webdriver.Chrome(
    options=options, executable_path=r"C:\chromedriver\chromedriver.exe"
)

try:
    driver.get("https://www.eredmenyek.com/foci/nemetorszag/bundesliga/")
    soup = BeautifulSoup(driver.page_source, "html.parser")

    for row in soup.select(".stats-table-container tr"):
        print("\t".join([e.text for e in row.select("td")]))

finally:
    driver.quit()

结果:

1.      Borussia Dortmund       20      15      4       1       51:20   49            
2.      Mönchengladbach 20      13      3       4       41:18   42            
3.      Bayern München  20      13      3       4       44:23   42            
4.      RB Leipzig      20      11      4       5       38:18   37            
5.      Frankfurt       20      9       5       6       40:27   32   
...         
© www.soinside.com 2019 - 2024. All rights reserved.