【问题标题】:python/Selenium --> find_elements_by_xpath method not finding all elementspython/Selenium --> find_elements_by_xpath 方法没有找到所有元素
【发布时间】:2020-08-14 14:45:00
【问题描述】:

我尝试使用 find_elements_by_xpath 从网站中提取 10 个元素,但它总是提取前四个元素。

这是我要提取的内容的屏幕截图(标有红点的行,它停在标有红十字的行):

这是我的python代码:

################################################################################
#   Déclaration et initialisation des variables globales
################################################################################

currentDirectory = os.getcwd()
path_to_website = "URL" #changed for stackoverflow question
path_to_chrome_profile = "path_to_chrome_profile" #changed for stackoverflow question

xpath_suggestions_text = "//li[@class='search-result search-result__occluded-item ember-view']"

################################################################################
#   Navigation sur google Chrome
################################################################################

# lancement de chrome avec le profil par défaut
options_ch = webdriver.ChromeOptions()
options_ch.add_argument("user-data-dir="+path_to_chrome_profile)

browser_chrome = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options_ch)

# on va sur la page réseau de linkedIn
browser_chrome.get(path_to_website )

list_elements = browser_chrome.find_elements_by_xpath(xpath_suggestions_text)


print(len(list_elements )) #prints 4 instead of 10


for profils in list_elements :
    print(element.text)
    print("////////")



browser_chrome.quit()

我尝试了很多东西,但没有任何效果..有什么线索吗? (我是网络抓取的初学者,请放纵:x)

谢谢大家

AJT

【问题讨论】:

  • 你试过只按类名搜索吗
  • 是的,我试过了,我没有找到任何东西 x),函数返回一个空列表
  • 您确定所有 10 个元素最初都存在于列表中吗?我猜其他元素是动态添加的
  • 不知道是不是这样,也许你是对的。我如何检查然后提取这些动态元素?
  • 不知道该告诉你什么。也许最好发布实际的 html。

标签: python selenium web-scraping


【解决方案1】:

您可能想尝试使用类选择器而不是 xpath。

browser.find_elements_by_class('search-result search-result__occluded-item ember-view')

如果不起作用,请尝试从父母到孩子。

div > ul

【讨论】:

  • find_elements_by_class_name 你的意思是?使用这一行,它找不到一个元素:/
  • 您可以尝试通过 css 选择器搜索:"li.search-result.search-result__occluded-item ember-view"。如果这不起作用,我会在 @AJT 上方查看 JaSON 的评论
  • 也不起作用,找到 0 个元素。好的,我正在等待他的回答 thks
【解决方案2】:

好的,我只需向下滚动即可加载网页和所有元素。我被直接显示网页所有元素的 chrome HTML 检查器欺骗了。

我认为@JaSON 的答案是正确的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 2021-06-22
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多