BeautifulSoup Python Selenium - 在抓取网站之前等待推文加载

时间:2021-04-29 10:16:29

标签: python python-3.x selenium beautifulsoup

我试图抓取一个网站来提取推文链接(在这种情况下特别是 DW),但我无法获取任何数据,因为推文没有立即加载,因此请求在有时间加载之前执行。我曾尝试使用请求超时以及 time.sleep() 但没有运气。使用这两个选项后,我尝试使用 Selenium 在本地加载网页并给它加载时间,但我似乎无法让它工作。我相信这可以用 Selenium 来完成。这是我到目前为止尝试过的:

        links = 'https://www.dw.com/en/vaccines-appear-effective-against-india-covid-variant/a-57344037'
        driver.get(links)
        delay = 30 #seconds
        try:
            WebDriverWait(driver, delay).until(EC.visibility_of_all_elements_located((By.ID, "twitter-widget-0")))
        except:
            pass
        tweetSource = driver.page_source
        tweetSoup = BeautifulSoup(tweetSource, features='html.parser')
        linkTweets = tweetSoup.find_all('a')
        for linkTweet in linkTweets:
            try:
                tweetURL = linkTweet.attrs['href']
            except:  # pass on KeyError or any other error
                pass
            if "twitter.com" in tweetURL and "status" in tweetURL:
                # Run getTweetID function
                tweetID = getTweetID(tweetURL)
                newdata = [tweetID, date_tag, "DW", links, title_tag, "News", ""]
                # Write to dataframe
                df.loc[len(df)] = newdata
                print("working on tweetID: " + str(tweetID))

如果有人能让 Selenium 找到这条推文就太好了!

1 个答案:

答案 0 :(得分:0)

这是一个 iframe 首先你需要切换到那个 iframe

iframe = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "twitter-widget-0"))
    )
driver.switch_to.frame(iframe)
相关问题