Selenium为何找不到reddit评论的ID?
我一直在用selenium来截取Reddit帖子和评论的截图,但遇到了一个问题,网上找不到解决办法。我的代码会把我想截图的对象的ID给selenium,对于主要的Reddit帖子,这个方法很好用。但是在评论部分,它总是超时(使用EC.presence_of_element_located()
时)或者说找不到(使用Driver.findElement()
时)。
这是我的代码:
def getScreenshotOfPost(header, ID, url):
driver = webdriver.Chrome() #Using chrome to define a web driver
driver.get(url) #Plugs the reddit url into the web driver
driver.set_window_size(width=400, height=1600)
wait = WebDriverWait(driver, 30)
driver.execute_script("window.focus();")
method = By.ID #ID is what I've found to be the most reliable method of look-up
handle = f"{header}{ID}" #The header will be of the form "t3_" for posts and "t1_" for comments, and the ID is the ID of the post of comment.
element = wait.until(EC.presence_of_element_located((method, handle)))
driver.execute_script("window.focus();")
fp = open(f'Post_{header}{ID}.png', "wb")
fp.write(element.screenshot_as_png)
fp.close()
我试过用ID、CLASS、CSS_SELECTOR和XPATH来查找,但都不行。我仔细检查过,格式t1_{评论的ID}
是评论的正确ID,无论是哪个Reddit帖子。增加我的网页驱动的等待时间也没有用。我不太确定问题出在哪里。
提前感谢任何帮助!
1 个回答
0
我明白问题出在哪里了……页面上有很多嵌套的影子根(shadow-roots)。如果你对IFRAME有了解,它们的行为很相似。简单来说,你需要把Selenium的上下文切换到IFRAME或影子根,这样Selenium才能看到里面的DOM结构并继续操作。你需要一个一个地切换到每个影子根,继续深入,直到找到你想要的元素。
这里有一些示例代码,
def test_recommended_code():
driver = Chrome()
driver.get('http://watir.com/examples/shadow_dom.html')
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
assert shadow_content.text == 'some text'
driver.quit()
你可以在这篇文章中了解更多信息。