繁体   English   中英

如何使用Python(没有第3方解析器)查找所有大写文本的链接?

[英]How to find links with all uppercase text using Python (without a 3rd party parser)?

我在一个简单的函数中使用BeautifulSoup来提取包含所有大写文本的链接:

def findAllCapsUrls(page_contents):
    """ given HTML, returns a list of URLs that have ALL CAPS text
    """
    soup = BeautifulSoup.BeautifulSoup(page_contents)
    all_urls = node_with_links.findAll(name='a')

    # if the text for the link is ALL CAPS then add the link to good_urls
    good_urls = []
    for url in all_urls:
        text = url.find(text=True)
        if text.upper() == text:
            good_urls.append(url['href'])

    return good_urls

大多数情况下都能正常工作,但是由于页面上HTML格式错误,导致少数页面无法在BeautifulSoup(或lxml,我也尝试过)中正确解析,从而导致对象中没有(或只有一些)链接。 “少数”听起来像不是一笔大买卖,但是此功能正在搜寻器中使用,因此可能有数百个页面搜寻器永远找不到...

如何将上述函数重构为不使用类似BeautifulSoup的解析器? 我一直在寻找如何使用正则表达式来执行此操作,但是所有答案都表明“使用BeautifulSoup”。 另外,我开始研究如何“修复”格式错误的HTML,以便对其进行解析,但我认为这不是最佳途径。

有什么其他解决方案,可以使用re或其他方式与上述功能相同?

如果html页面格式错误,则没有很多可以真正帮助您的解决方案。 BeautifulSoup或其他解析库是解析html文件的方法。

如果您想引用库路径,则可以使用正则表达式来匹配所有链接,请参见使用[AZ]范围的Regular-expression-to-extract-url-from-an-html-link

当我需要解析一个真正损坏的html且速度不是最重要的因素时,我使用selenium&webdriver自动化了浏览器。

这是我所知道的最难的html解析方法。 检查本教程,它显示了如何使用WebDriver提取Google建议(代码在Java中,但可以更改为python)。

我最终得到了正则表达式和BeautifulSoup的组合:

def findAllCapsUrls2(page_contents):
    """ returns a list of URLs that have ALL CAPS text, given
    the HTML from a page. Uses a combo of RE and BeautifulSoup
    to handle malformed pages.
    """
    # get all anchors on page using regex
    p = r'<a\s+href\s*=\s*"([^"]*)"[^>]*>(.*?(?=</a>))</a>'
    re_urls = re.compile(p, re.DOTALL)
    all_a = re_urls.findall(page_contents)

    # if the text for the anchor is ALL CAPS then add the link to good_urls
    good_urls = []
    for a in all_a:
        href = a[0]
        a_content = a[1]
        a_soup = BeautifulSoup.BeautifulSoup(a_content)
        text = ''.join([s.strip() for s in a_soup.findAll(text=True) if s])
        if text and text.upper() == text:
            good_urls.append(href)

    return good_urls

到目前为止,这适用于我的用例,但我不能保证它可以在所有页面上使用。 另外,仅当原始功能失败时,我才使用此功能。

暂无
暂无

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

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