我试图点击一些图像链接,然后检索 url 并将它们另存为 jpg。我一直在我要检索的图像 url 之前检索页面的 url。
它保存带有时间戳的 jpgs 文件,但没有图像,因为我得到了错误的 url。
ts = time.time()
WebDriverWait(driver, 100).until(
EC.presence_of_element_located((By.XPATH, "/html/head/meta")))
img_url = driver.current_url
print img_url
urllib.urlretrieve(img_url, "/home/ro/A_Python_Scripts/tumblrr_auto/Pics/test_pics/%d.jpg" %(ts))
当我点击链接时,我得到一些这样的 html。
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height;">
<link rel="stylesheet" href="resource://gre/res/ImageDocument.css">
<link rel="stylesheet" href="resource://gre/res/TopLevelImageDocument.css">
<link rel="stylesheet" href="chrome://global/skin/media/TopLevelImageDocument.css">
<title>3760968-1135171246-cc%5B.jpg (JPEG Image, 704 × 400 pixels) - Scaled (91%)</title>
我可以通过隐式等待让它工作,但我确实需要一个显式等待。
请您参考如下方法:
我认为问题在于您正在等待 META 标记存在。它可能已经存在于您启动的页面上,因此无需等待,执行会继续,从而为您提供当前页面的 URL。
在这种情况下,我通常会做以下两件事之一:
- 要么等待第二页上的特定(唯一)元素……第二页上存在但第一页上不存在的元素。
或
- 等待第一页上的某个元素过时(表明浏览器正在更改页面),然后获取我想要的元素(从第二页)
我对你的页面了解不够,无法提供具体代码,但这里有一些例子
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "some id that exists on page2 but not on page1")))
// once the line above passes, I know I'm on the second page... do stuff
或
WebDriverWait(driver, 10).until(EC.staleness_of((By.ID, "some id that exists on page1 but not on page2")))
// once the line above passes, I know I'm transitioning to the second page... do stuff...
// may need to wait for an element on the 2nd page to exist, be clickable, etc.
上面的示例使用了 ID,但这些 ID 可能不可用,因此您可以将它们更改为适用的任何内容。
