Web爬网(类名更改)

我正在使用硒为我的项目下载一些图像!

要下载图像,我使用以下命令行:

import networkx as nx
%matplotlib inline
import matplotlib.pyplot as plt
#draw complete bi-partite graph
plt.figure(figsize=(10,7))
cbg= nx.complete_bipartite_graph(20,15)
nx.draw_networkx(cbg)
p = nx.closeness_centrality(cbg)        
for a,b in p:
    s.append(b)
plt.bar(cbg.nodes,s,align='center',alpha=1)
plt.show()

然后,使用image_url下载图像。

问题在于,经过多次尝试,类名更改为“ main-lazy”。

我可以手动将“ main”更改为“ main-lazy”。有什么办法可以通过代码来做到这一点。

我正在寻找一种方法来告诉代码,要么找到“ main-lazy”的类名,要么找不到“ main”的类名!

jrr1234567 回答:Web爬网(类名更改)

为什么不try/except

try:
   image_lm = prd.find_element_by_class_name('main')
except Exception as e:
   print("changing to main_lazy \n"+e)
   image_lm = prd.find_element_by_class_name('main_lazy')
,

如果仅有两个变体是“ main”和“ main-lazy”,则可以尝试使用:

By.XPath("//[contains(@class,'main')]

对不起,这是C#的变体,但我相信您可以弄清楚Python的等效版本。

,

您可以使用

的css或语法
image_lm = prd.find_element_by_css_selector('.main,.main-lazy')
,

ClassName为 main-lazy 表示元素是通过加载的。在这种情况下,您必须引入 WebDriverWait ,然后可以使用通过lambda表达式组合两个元素的合并检查,如下所示:

  • 使用class_name 1:

    image_lm = WebDriverWait(driver,20).until(lambda x: (x.find_element_by_class_name("main"),x.find_element_by_class_name("main-lazy")))
    
  • 使用class_name 2:

    image_lm = WebDriverWait(driver,20).until(lambda driver: driver.find_element(By.CLASS_NAME,"main") and driver.find_element(By.CLASS_NAME,"main-lazy"))
    

作为替代方案,您可以使用等效的合并两个元素的合并检查,如下所示:

  • 使用css_selector

    image_lm = WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,".main,.main-lazy")))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  

您可以在selenium two xpath tests in one

中找到相关的讨论
本文链接:https://www.f2er.com/3063795.html

大家都在问