Python 试图找到img类的src attrib时的奇怪行为
我正在尝试收集鞋子的图像,这是我的简化代码:Python 试图找到img类的src attrib时的奇怪行为,python,selenium,Python,Selenium,我正在尝试收集鞋子的图像,这是我的简化代码: browser.get('https://www.gumtree.com.au/s-men-s-shoes/tn/k0c18573?ad=') recents = browser.find_element_by_xpath("//div[@class='panel search-results-page__main-ads-wrapper user-ad-collection user-ad-collection--row']") ads = rec
browser.get('https://www.gumtree.com.au/s-men-s-shoes/tn/k0c18573?ad=')
recents = browser.find_element_by_xpath("//div[@class='panel search-results-page__main-ads-wrapper user-ad-collection user-ad-collection--row']")
ads = recents.find_elements_by_xpath(".//a")
for ad in ads:
img = ad.find_element_by_xpath(".//img").get_attribute('src')
这很奇怪,因为它会在某些广告中找到“src”属性,而在其他广告中却找不到。我甚至试过:
img = ''
while img == '':
img = ad.find_element_by_xpath(".//img").get_attribute('src')
它将永远运行。任何关于为什么会发生这种情况的想法都将受到欢迎我将重构您的代码,直接查询广告的图像元素,而不是试图查找所有嵌套元素。这是更有效的 我还要添加
WebDriverWait
,以便在定位图像元素之前为页面提供加载时间。然后,我们可以迭代图像元素并获得它们的src
属性
这里要添加的另一件事是使用ActionChains
调用move\u to\u元素
。此网站上的img
元素使用延迟加载,因此src
属性在我们滚动到它们之前实际上不可见
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
browser.get('https://www.gumtree.com.au/s-men-s-shoes/tn/k0c18573?ad=')
# returns 24 image elements, one for each ad
most_recent_images = WebDriverWait(browser, 20).until(
EC.presence_of_all_elements_located((By.XPATH, "//section[div/div[text()='Most recent']]/div/div/a//img")))
# declare action chains
#actions = ActionChains(browser)
for image in most_recent_images:
# scroll to element
#actions.move_to_element(image).perform()
# scroll into view using javascript
browser.execute_script("arguments[0].scrollIntoView(true);", image)
# get src attribute
print(image.get_attribute("src"))
browser.close()
browser.quit()
我运行了这个完整的代码示例,并成功打印了24个图像链接
不同的部分有不同类型的图像。你需要用你正在寻找的图片更新这个问题。这里的问题似乎是延迟加载和使用move_to_元素修复了这个问题,谢谢!一个问题是,当我在循环中运行move_to_元素时,它会从循环和它之前的每个元素移动到元素。所以,当它到了第五个项目,它会去第一,然后第二。。。等5号。这是一个问题,因为循环越深入,所需时间将呈指数增长。有趣的是,看看这里的循环结构,
move\u to\u element
应该每个元素只发生一次-如果有嵌套循环,我可以看到这是如何发生的。让我试一下这段代码,看看javascriptscrollIntoView
是否是将图像移动到视口中的更好选项。我会用我的发现和可能更新的答案再次标记你@moo5e我运行了代码,并观察到了与move\u to\u element
相同的事情,这很奇怪。我用Javascript替换了它,现在它运行得更快了。