Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式捕获带有类名的html元素_Python_Html_Regex - Fatal编程技术网

Python 正则表达式捕获带有类名的html元素

Python 正则表达式捕获带有类名的html元素,python,html,regex,Python,Html,Regex,我正在尝试使用python获取html文件中所有元素的元素和类名。我用下面的代码设法得到了所有的类名。它是这样写的,因为我将在存储带有类名的元素时浏览大量html文件。忽略没有类名的元素 temp_file = open(root + "/" + file, "r", encoding="utf-8-sig", errors="ignore") temp_content = temp_file.read() class_names = re.findall("class=\"(

我正在尝试使用python获取html文件中所有元素的元素和类名。我用下面的代码设法得到了所有的类名。它是这样写的,因为我将在存储带有类名的元素时浏览大量html文件。忽略没有类名的元素

 temp_file = open(root + "/" + file, "r", encoding="utf-8-sig", errors="ignore")
    temp_content = temp_file.read()
    class_names = re.findall("class=\"(.*?)\"", temp_content)
但是现在我正在努力找到一种方法来获取类所属的元素。请记住,元素有时会相互重叠,因此readlines()也不会有太大帮助,而且可能比一次重新生成整个文档要慢

<div class="header_container container_12">
        <div class="grid_5">
              <h1><a href="#">Logo Text Here</a></h1>
        </div>
        <div class="grid_7">
            <div class="menu_items"> 
                <a href="#" class="home active">Home</a><a href="#" class="portfolio">Portfolio</a> 
               <a href="#" 
                class="about">About Me
                </a><a href="#" class="contact">Contact Me</a> 
            </div>
        </div>
</div>

Regex是HTML解析的一个糟糕选择,但幸运的是,对于美化组来说,这是微不足道的:

from bs4 import BeautifulSoup

html = """<div class="header_container container_12">
        <div class="grid_5">
              <h1><a href="#">Logo Text Here</a></h1>
        </div>
        <div class="grid_7">
            <div class="menu_items"> 
                <a href="#" class="home active">Home</a><a href="#" class="portfolio">Portfolio</a> 
               <a href="#" 
                class="about">About Me
                </a><a href="#" class="contact">Contact Me</a> 
            </div>
        </div>
</div>"""

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    print(elem.attrs["class"], elem.name)
您可以根据需要将其放入dict中,但要小心,因为每个bucket可能映射到多个元素。它告诉您的只是一个元素存在,并且有一个特定的标记名,给定一个特定的类名字符串或元组,以特定的顺序排列

elems = {}

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    elems[tuple(elem.attrs["class"])] = elem.name

for k, v in elems.items():
    print(k, v)

<>我认为ReGEX是这个工作的错误工具,考虑将HTML加载到DOM文档中,然后用DOM选择器解析它。 下面的示例是javascript,因为它允许我将其作为可运行的代码段包含在内,但它应该足够解释该方法,以便您创建python等效代码

var classElements=document.querySelectorAll(“[class]”);
对于(i=0;i


您是否考虑过改为解析DOM?HTML和正则表达式不是好朋友。使用解析器,它更简单、更快、更易于维护。感谢您提供的解决方案,因为它无法找到“lxml”,所以不得不切换到“html.parser”。作为一个附带的问题,是否有一个简单的方法来获得什么元素下使用美丽的汤?因此,在上面的html中,获取“header\u container”作为所有其他元素的父元素,“menu items”作为“a”元素的父元素。当然,请参阅和。
elems = {}

for elem in BeautifulSoup(html, "lxml").find_all(attrs={"class": True}):
    elems[tuple(elem.attrs["class"])] = elem.name

for k, v in elems.items():
    print(k, v)