繁体   English   中英

检查python的页眉,正文或页脚中是否存在元素

[英]Check if element is present in header, body or footer selenium python

以本网站为例:

https://www.imglobal.com

联系人号码出现在网站的正文中 在此处输入图片说明 某些站点在顶部以及菜单选项卡位于顶部,而某些站点在底部页脚。

我已经开发了使用以下方法定位元素及其位置的例程

    element.location
    element.location_once_scrolled_into_view

并滚动到该元素的视图

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

有没有一种方法可以借助标签借助python中的硒或bs4来直接解释该元素是否存在于网页的页眉/正文/页脚中?

编辑

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

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

您能否仅使用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

暂无
暂无

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

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