【问题标题】:Which one is the same as find_(findTag, class_=findValue) of BeautifulSoup in webDriver?哪一个和webDriver中BeautifulSoup的find(find Tag, class_=find Value)是一样的?
【发布时间】:2017-02-27 06:29:18
【问题描述】:

我想在 Selenium 中使用 BeautifulSoup 的相同查找方法 find(findClass, class_=findValue),我搜索了但没有我需要的,你能帮帮我吗?

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    你可以把你的 BeautifulSoup 代码翻译成相当强大的 CSS 选择器表达式,然后使用 find_elements_by_css()

    # equivalent to : soup.find("div", class_="list-container")
    driver.find_element_by_css("div.list-container")
    
    # equivalent to : soup.find("div", class_="list-container").find_all("a")
    driver.find_elements_by_css("div.list-container a")
    

    【讨论】:

    • link = soup.find("div", class_="list-container").find_all("a"), href = link.get("href"),上面的代码是可以的。但是您的两个答案都得到了相同的例外....
    • 正如 Alex 指出的,你需要学习 Selenium 的 API,阅读文档。在 selenium 中,您在单个 web 元素上调用 get_attribute("href") 以获取属性值...
    • 我是通过 get_attribute 得到的。感谢您的意见。 @har07
    • 我怎样才能把这个soup.find(findTag, id=findValue).find_all(linkTag) 转换成driver.find_elements_by.....?
    • CSS 选择器表达式为:findTag#findValue linkTagfindTag[id="findValue"] linkTag。了解更多关于CSS selector
    【解决方案2】:

    这就是你要找的东西:

    elements = []
    classes = driver.find_elements_by_class(className)
    for c in classes:
        l = c.find_elements_by_tag_name(tagName)
        if l:
            elements.extent(l)
    

    等价于

    soup.findAll("div", { "class" : className})
    

    【讨论】:

    • 对不起,我原来的代码是soup.find("div", class_="list-container").find_all("a"),所以driver.find_elements_by_class("list-container")是好吗?
    • @mikezang 您需要使用 for 循环来提取 a
    • 问题是我使用该结果来获取(“href”),但您的代码无法获取,错误是 Exception: 'WebElement' object has no attribute 'get'...跨度>
    • @mikezang beautifulsoup 和 selenium web 驱动程序是不同的......你不能只是在 selenium 中“使用”beautifulsoup 中的方法...... har07 的解决方案应该会给你带来结果。
    【解决方案3】:

    如果您需要执行一些任务,例如单击按钮,请使用 selenium API。

    如果你需要从 HTML 代码中提取数据,你应该使用 BeautiflSoup。

    您可以使用 selenium 获取 HTML 代码,然后使用 BeautifulSoup 进行解析:

    html_source = browser.page_source
    soup = BeautifulSoup(html_source)
    

    【讨论】:

    • 我的问题是如何避免使用BeautifulSoup....,如果使用VeautifulSoup,我的代码是可以的:)
    猜你喜欢
    • 2012-07-15
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多