Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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
如何将HTML列表条目提取到Python列表中?_Python_Regex - Fatal编程技术网

如何将HTML列表条目提取到Python列表中?

如何将HTML列表条目提取到Python列表中?,python,regex,Python,Regex,可能重复: 我有一长串类似于以下内容的HTML: <ul> <li><a href="/a/long/link">Class1</a></li> <li><a href="/another/link">Class2</a></li> <li><img src="/image/location" border="0">Class3</a></li&

可能重复:

我有一长串类似于以下内容的HTML:

<ul>
<li><a href="/a/long/link">Class1</a></li>
<li><a href="/another/link">Class2</a></li>
<li><img src="/image/location" border="0">Class3</a></li>
</ul>
等等

我该怎么做呢?我尝试过使用REs,但是我还没有找到一个有效的方法。当然,只有8个类,我可以很容易地手动完成,但我还有几个HTML文档可以从中提取数据


谢谢!:)

如果所有的行尾都相同,可以尝试使用如下正则表达式

re.compile(r'^<li><.*>(.*)</a></li>$')
重新编译(r'^
  • (.*)
  • $)
    如果您希望文件的可变性比示例中的要大得多,那么像HTML解析器这样的东西可能会更好。

    这应该是可行的,但可以将其视为一种快速而丑陋的攻击

    >>hdata=“”
    • 第三类 “…
    ” >>>进口稀土 >>>lire=re.compile(r'
  • *?>(.*?)检查lxml(pip安装lxml)。您可能想做更多的研究,但实际上可以归结为以下内容:

    from lxml import etree
    
    tree = etree.HTML(page_source)
    def parse_list(xpath):
        ul = tree.xpath(xpath)
        return [child.text for child in ul.getchildren()]
    

    如果您想要一个HTMLParserTry BeautilSoup的示例,请查看文档:
    soup=BeautilSoup(html);soup2.findAll(“li”,text=True);
    ,它将返回所有类名。另请参见。谢谢!我确实使用了Beautiful Soup将列表与HTML文档的其余部分隔离,但不确定如何进一步。我将查看它:)
    >>> hdata = """<ul>
    ... <li><a href="/a/long/link">Class1</a></li>
    ... <li><a href="/another/link">Class2</a></li>
    ... <li><img src="/image/location" border="0">Class3</a></li>
    ... </ul>"""
    >>> import re
    >>> lire = re.compile(r'<li>.*?>(.*?)<.*')
    >>> [lire.search(x).groups()[0] for x in hdata.splitlines() if lire.search(x)]
        ['Class1', 'Class2', 'Class3']
    
    from lxml import etree
    
    tree = etree.HTML(page_source)
    def parse_list(xpath):
        ul = tree.xpath(xpath)
        return [child.text for child in ul.getchildren()]