【问题标题】:BeautifulSoup Python Selenium - Wait for tweet to load before scraping websiteBeautifulSoup Python Selenium - 在抓取网站之前等待推文加载
【发布时间】:2021-04-29 10:16:29
【问题描述】:

我正在尝试抓取网站以提取推文链接(在这种情况下特别是 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 找到这条推文,那就太好了!

【问题讨论】:

    标签: python python-3.x selenium beautifulsoup


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!无论“twitter-widget-0”是否存在,有没有办法让它等待?因为某些推文仍然由于某种原因而溜走,所以我希望每个网站都等待 15 秒。
    • 您只需添加time.sleep
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多