繁体   English   中英

Python WebDriver:find_element() 找不到元素

[英]Python WebDriver: find_element() not finding the element

我正在按照使用 Python 自动化无聊的东西的第 12 章学习 Web Scraping 的基础知识,但是我遇到了 find_element() 方法的问题。 当我使用该方法查找类名为“card-img-top cover-thumb”的元素时,该方法不返回任何匹配项。 但是,该代码确实适用于本书中示例以外的 URL。

为了让代码做任何事情,我不得不对编写的代码进行相当多的更改。 我已经在 GitHub HERE上发布了完整的代码,但总结一下:

  • 这本书说要使用“find_element_by_*”方法,但这些方法会产生折旧消息,指示我改用 find_element()。

  • 要使用这种其他方法,我导入“By”。

  • 我还从“Selenium.Webdriver.Chrome.Service”导入“服务”,因为 Chromedriver 无法正常工作。

  • 我还使用 Webdriver.ChromeOptions() 定义了选项,这些选项隐藏了有关故障设备的某些错误消息,显然你应该忽略这些错误消息?

  • 我将书中的代码放入带有“url”和“classname”参数的函数中,这样我就可以测试不同的 url,而无需重复编辑代码。

这是代码的“业务部分”:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service  
from selenium.webdriver.common.by import By

s=Service(r'C:\Users\antse\AppData\Local\Chrome_WebDriver\chromedriver.exe')

op = webdriver.ChromeOptions()
op.add_experimental_option('excludeSwitches', ['enable-logging'])

def FNC_GET_CLASS_ELEMENT_FROM_PAGE(URL, CLASSNAME):       
    browser = webdriver.Chrome(service = s, options = op)
    browser.get(URL)
    try:  
        elem = browser.find_element(By.CLASS_NAME, CLASSNAME)
        print('Found <%s> element with that class name!' % (elem.tag_name))
    except:
        print('Was not able to find an element with that name.')

FNC_GET_CLASS_ELEMENT_FROM_PAGE('https://inventwithpython.com', 'card-img-top cover-thumb')

预期输出:找到具有该类名的 <img> 元素!

由于当我查看 Wikipedia 之类的网站时代码确实有效,我想知道是否对页面的 html 进行了更改以防止抓取正常工作?

本书章节的链接在这里

我很感激你能给我的任何建议!

您不能将多个类传递给find_element 只有一个可以在场。 所以替换这个:

FNC_GET_CLASS_ELEMENT_FROM_PAGE('https://inventwithpython.com', 'card-img-top cover-thumb')

有了这个:

FNC_GET_CLASS_ELEMENT_FROM_PAGE('https://inventwithpython.com', 'card-img-top')

如果你真的想同时使用这两个类,那么看看这个答案,它详细解释了事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM