首页 > 解决方案 > Python Selenium find_elements_by_class_name 错误

问题描述

我正在抓取一个返回 Linkedin 个人资料链接的谷歌页面。

我想收集页面上的链接并将它们放在 python 列表中。

问题是我似乎无法从页面中正确提取它们,我不知道为什么。

谷歌源代码如下所示:

该页面显示以下 10 项:

Mary Smith - Director of Talent Acquisition ...
https://www.linkedin.com › marysmith
Anytown, Arizona 500+ connections ... Experienced Talent Acquisition Director, with a 
demonstrated history of working in the marketing and advertising ...

源代码如下所示:

<div data-hveid="CAIQAA" data-ved="2ahUKEwjLv6HMr4HmAhWluVkKHfjfA1EQFSgAMAF6BAgCEAA">
   <div class="rc"> 
       <div class="r">
           <a href="https://www.linkedin.com/in/marysmith" ping="/url?sa=t&amp;source=web&amp;rct=j&amp;url=https://www.linkedin.com/in/marysmith&amp;ved=2ahUKEwjLv6HMr4HmAhWluVkKHfjfA1EQFjABegQIAhAB">
               <h3 class="LC20lb"><span class="S3Uucc">Mary Smith - Director of Talent Acquisition, Culture Curator ...</span></h3><br>
               <div class="TbwUpd">
                   <cite class="iUh30 bc">https://www.linkedin.com › marysmith</cite>
              </div>
           </a>
           ...

在我的脚本中,我使用 Selenium 并find_element_by_class_name()收集到 Linkedin 链接的所有实例。上例中的一个是https://www.linkedin.com › marysmith. driver.find_element_by_class_name()这是我与特定类名一起使用的一行代码:

linkedin_urls = driver.find_element_by_class_name("iUh30 bc")

但是我收到以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="iUh30 bc"]"}

我尝试了各种排列和其他类,但它不起作用。如果我将 X_Path 用于其中一个链接,则脚本将返回该单个链接。

我究竟做错了什么?

标签: pythonseleniumweb-scraping

解决方案


像 Google 和 Facebook 这样的网站使用 AI 来构建页面源并分配随机类,这就是为什么您没有获得此类元素的原因,因为每次加载该页面时,类的值都会变化 要解决此问题,请尝试使用常量标签或属性。

尝试类似:

#<cite class="iUh30 bc">https://www.linkedin.com › mary-smith-mckenzie-8b660799</cite>
driver.find_elements_by_xpath("//cite[contains(text(),'›') and contains(text(),'linkedin.com')]")

推荐阅读