如何在python中通过selenium加载网站的所有评论

2024-06-28 10:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从https://www.focus.de/gesundheit/news/coronavirus-news-trump-prahlt-mit-allumfassender-macht_id_11576018.html中删除所有评论(~7000)。由于该网站不显示所有评论,但一次只能加载10条评论,因此我尝试使用python中的selenium加载所有评论,然后将输出提供给BeautifulSoup

与按钮“Weitere Kommentare(10)”对应并加载下10条评论的网站HTML段为:

<div id="further_comments" class="getMoreComments">                 
    <a rel="1" class="moreComments bluebutton">
         <span>Weitere Kommentare (10)</span>
    </a>                        
</div>

它加载接下来的十条注释(下面的第二个div,这里只显示一条而不是十条)和一个用于加载另外十条注释的新按钮(a):

<div class="moreComments">
    <div class="comment clearfix open oid-15051615"</div>
    <div class="getMoreComments">
        <a class="moreCommentsAjx bluebutton" rel="1"></a>
    </div>
</div>

我的方法是编写一个脚本,自动单击“Weitere Kommentare(10)”,等待下一个10条评论和下一个按钮“Weitere Kommentare(10)”加载,找到按钮,再次单击它。。。直到加载所有注释。我的尝试如下(我将按钮居中,以避免页面底部出现弹出窗口,使按钮模糊):

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException

ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get('https://www.focus.de/gesundheit/news/coronavirus-news-trump-prahlt-mit-allumfassender-macht_id_11576018.html')
driver.fullscreen_window()

button = driver.find_element_by_class_name("moreComments.bluebutton")
driver.execute_script('arguments[0].scrollIntoView({block: "center", inline: "center"})', button)
driver.execute_script("arguments[0].click();", button)

while driver.find_element_by_class_name("moreCommentsAjx.bluebutton"):
    element = WebDriverWait(driver, 10, ignored_exceptions=ignored_exceptions).until(EC.visibility_of_element_located((By.CLASS_NAME, "moreCommentsAjx.bluebutton")))
    driver.execute_script('arguments[0].scrollIntoView({block: "center", inline: "center"})', element)
    element.click()

page_source = driver.page_source

不幸的是,这些代码从未通过。在某个点上,“Weitere Kommentare(10)”按钮不再出现,并且抛出了一个“NoTouchElementException:无法定位元素:.MoreComentsajx.bluebutton”(奇怪的是,尽管它应该忽略它)。让我困惑的是,它不是系统的。有时,它会在失败之前加载数百条注释,有时只有30条,等等。偶尔,当滚动似乎失败且按钮未居中时,会抛出StaleElementReferenceException(同样,它不应该,但确实会)

提前感谢您的帮助


Tags: fromimportdivdriverselenium评论element按钮
1条回答
网友
1楼 · 发布于 2024-06-28 10:57:34

你可能等错了

点击之后,你会一直等到按钮出现,但它可能还在,还没有消失

单击后,您希望等待按钮消失(但不会失败并有很短的超时),然后您希望等待按钮再次出现

相关问题 更多 >