【问题标题】:Trying to print out a line on a webpage试图在网页上打印一行
【发布时间】:2022-01-27 03:47:49
【问题描述】:

我正在尝试使用 selenium 打印一组网页的行。

到目前为止,这是我的一段代码。

import selenium
from selenium import webdriver as wb
webD=wb.Chrome("C:\Program Files (x86)\chromedriver.exe")
webD.get('https://www.flashscore.com/')

webD.maximize_window() # For maximizing window
webD.implicitly_wait(2) # gives an implicit wait for 20 seconds
webD.find_element_by_id('onetrust-reject-all-handler').click()

matchpages = webD.find_elements_by_class_name('preview-ico.icon--preview')
for matchpages in matchpages:
    matchpages.click()

现在,我想通过以下方式在网页上显示完整的文本:

driver.find_element(By.CLASS_NAME,"smallArrow-ico").click()

应该对 for 循环中的每个网页都执行此操作。

除此之外,我还想打印以下行:

main = driver.find_element(By.XPATH,"//div[@class='previewLine' and ./b[text()='Hot 
stat:']]").text
main = main.replace('Hot stat:','')
print(main)

如何在 for 循环中包含两段文本?

提前致谢。

【问题讨论】:

    标签: selenium web-scraping


    【解决方案1】:

    您尝试点击的元素有点棘手。
    试试这个:

    matchpages = webD.find_elements_by_xpath("//*[@class='preview-ico icon--preview']//*[name()='use']")
    for matchpages in matchpages:
        matchpages.click()
    

    单击上方的元素会打开一个新窗口。因此,您必须切换到新窗口句柄才能访问那里的元素,完成后关闭它并切换到主窗口以继续在那里工作。
    所以你的代码可以是这样的:

    wait = WebDriverWait(driver, 20)
    matchpages = webD.find_elements_by_xpath("//*[@class='preview-ico icon--preview']//*[name()='use']")
    for matchpages in matchpages:
        matchpages.click()
        new_window = driver.window_handles[1]
        original_window = driver.window_handles[0]
        driver.switch_to_window(new_window)
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.previewShowMore.showMore"))).click()
        main = driver.find_element(By.XPATH,"//div[@class='previewLine' and ./b[text()='Hot stat:']]").text
        main = main.replace('Hot stat:','')
        print(main)
        driver.close()
        driver.switch_to_window(original_window)
    

    要使用网络驱动程序等待,您需要以下导入:

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

    【讨论】:

    • 是的,我明白了。然而,这行得通。现在我还想查看整页并打印一段文字,如上所述。如何将它包含在 for 循环中?
    • 好的,我添加了所有必需的代码来完成您要求的所有内容。如果仍有问题,请告诉我
    • 这似乎确实是解决方案,谢谢!还有一个问题:我想从网站上的所有页面中获取所有“热门统计数据”。这意味着它必须选择所有预览。现在它只选择 1 个预览。如何在代码中进行调整?提前谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2012-01-21
    • 2011-12-07
    • 1970-01-01
    相关资源
    最近更新 更多