首页 > 解决方案 > 为什么这段代码中http-response的html文件不完整?

问题描述

我正在尝试通过使用 python 和模块“requests”和“BeautifulSoup”从网站(https://www.evaschulze-aufgabenpool.de/index.php/s/smwP6ygck2SXRtF)获取一些数据,但似乎我得到一个不完整的 html 文件作为响应。例如,当使用浏览器检查时,与原始 html 文件相比,作为响应,我得到的 html 文件中的 table 标记缺少行。所以我的问题是:这是什么原因,我该如何解决这个问题?

这是我用来获取表格标签内数据的代码:

import requests
from bs4 import BeautifulSoup

source = requests.get("https://www.evaschulze-aufgabenpool.de/index.php/s/smwP6ygck2SXRtF").text
soup = BeautifulSoup(source, "html.parser")
for table in soup.find_all("table"):
    print(table)

标签: pythonweb-scrapingbeautifulsouppython-requests

解决方案


怎么了?

表格内容是动态生成的,不包含在您的请求响应中。您必须等到页面/内容加载完毕。

你可以做的是使用硒

from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep

url = "https://www.evaschulze-aufgabenpool.de/index.php/s/smwP6ygck2SXRtF"

driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')

driver.get(url)
#driver.implicitly_wait(10) 
sleep(3)
soup = BeautifulSoup(driver.page_source,"lxml")

for table in soup.find_all("table"):
    print(table)

driver.close()

推荐阅读