【问题标题】:Check if element is present in header, body or footer selenium python检查元素是否存在于页眉、正文或页脚 selenium python
【发布时间】:2020-01-13 02:11:03
【问题描述】:

以本站为例:

https://www.imglobal.com

联系电话在网站正文中 某些网站将其与菜单选项卡一起放在顶部,而某些网站位于底部页脚。

我已经开发了用于定位元素及其位置的例程

    element.location
    element.location_once_scrolled_into_view

并滚动到元素的视图中

    browser.execute_script("arguments[0].scrollIntoView()", element)

有没有办法直接解释元素是否存在于网页的页眉/正文/页脚中,在标签的帮助下,在 python 中使用 selenium 或 bs4。

编辑

标题示例: https://www.moeck.com/

页脚示例: https://www.andrew-kelly.co.uk/

【问题讨论】:

    标签: python selenium selenium-webdriver beautifulsoup


    【解决方案1】:

    你能不能只使用element.parent 并循环直到找到你的目标标签之一?

    像这样的:

    from bs4 import BeautifulSoup as soup
    
    html = """<html><header><div><span class="phone">123456789</span></div><body><div></div><footer><div></div></footer>"""
    location = ['header','body','footer']
    page = soup(html, 'html.parser')
    
    element = page.find('span',{'class':'phone'})
    
    while (element.parent):
        if element.parent.name in location:
            print("Phone is in " + element.parent.name)
            break
        else:
            element = element.parent
    

    编辑:

    也检查类名:

    from bs4 import BeautifulSoup as soup
    
    html = """<html><header class='test-class'><div><span class="phone">123456789</span></div><body><div></div><footer><div></div></footer>"""
    location = ['header','body','footer']
    soup = BeautifulSoup(html, 'html.parser')
    
    element = soup.find('span',{'class':'phone'})
    
    while (element.parent):
        if element.parent.name in location and 'test-class' in element.parent.get('class'):
            print("Phone is in " + element.parent.name)
            break
        else:
            element = element.parent
    

    【讨论】:

    • 感谢您的建议。 parent.name 是查找标签名还是类名?我想我们可以使用 element.parent['class'] 作为类名。
    • 如何获取父类/id 名称?
    • @LakshmiNarayanan 您可以在element.parent 上添加get('class')。小心,它会返回一个列表。查看我的编辑:-)
    • 感谢@Maaz 的编辑。我刚刚意识到,我查找元素的例程对于硒来说更通用。因此,我使用 selenium 的 get_attribute() 转换了您的例程。有没有办法使用 selenium 获取元素的标签,类似于使用 bs4 的 .name
    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 2021-05-17
    • 2014-06-23
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多