首页 > 解决方案 > 由于无限页面加载,无法通过 python 中的 selenium 进行抓取

问题描述

我正在尝试提取一些新闻文章的内容。某些 url 需要登录才能访问完整内容。我决定使用 selenium 自动登录。但是,我无法提取内容,因为第一个 url 需要永远加载并且永远不会到达实际文本提取完成的地步。它最终抛出超时异常。

这是我的代码

for url in url_list:
    chrome_options = Options()
    ua = UserAgent()
    userAgent = ua.random
    options.add_argument(f'user-agent={userAgent}')
    driver = webdriver.Chrome(ChromeDriverManager().install(), options = chrome_options)
    driver.get(url)
    time.sleep(5)
    frame = driver.find_elements_by_xpath('//iframe[@id="wallIframe"]')
    #Some articles require going through a paywall and some don't
    if len(frame)==0:
        text_element = driver.find_elements_by_xpath('//section[@id="main-content"]//article//p')
        text = " ".join(x.text for x in element)
    else:
        text = log_in(frame)
    driver.quit()

尽管代码从未到达过它,但这是我的 log_in 方法

def log_in(frame):
    driver.switch_to.frame(frame[0])
    driver.find_element_by_id("PAYWALL_V2_SIGN_IN").click()
    time.sleep(2)
    driver.find_elements_by_id("username")[0].send_keys(username)
    time.sleep(2)
    driver.find_elements_by_xpath('//button[text()="Continue"]')[0].click()
    time.sleep(1)
    driver.find_elements_by_id("password")[0].send_keys(password)
    time.sleep(1)
    element = driver.find_elements_by_xpath('//button[@type="submit"]')[0].click()
    time.sleep(1)
    text = parse_text(element)

我怎样才能解决这个问题?

标签: pythonseleniumweb-scraping

解决方案


与其手动设置超时time.sleep,不如使用WebDriverWaitwith expected_conditions; 这样,只有在满足特定条件时(例如,如果元素可见或元素可单击),才会对元素执行的操作。

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

try:
    frame = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="wallIframe"]')))

except TimeoutException:
    print "Element not found."

推荐阅读