gpt4 book ai didi

python - 使用正则表达式搜索关键字附近的 HTML 链接

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:16 25 4
gpt4 key购买 nike

如果我正在寻找关键字“sales”并且我想获得最近的“http://www.somewebsite.com”,即使文件中有多个链接。我想要最近的链接而不是第一个链接。这意味着我需要搜索关键字匹配之前的链接。

这行不通...


正则表达式 = (http|https)://[-A-Za-z0-9./]+.*(?!((http|https)://[-A-Za-z0-9./]+ ))销售量
销售量

找到最接近关键字的链接的最佳方法是什么?

最佳答案

通常使用 HTML 解析器比使用正则表达式更容易和更可靠。

使用第三方模块lxml :

import lxml.html as LH

content = '''<html><a href="http://www.not-this-one.com"></a>
<a href="http://www.somewebsite.com"></a><p>other stuff</p><p>sales</p>
</html>
'''

doc = LH.fromstring(content)
for url in doc.xpath('''
//*[contains(text(),"sales")]
/preceding::*[starts-with(@href,"http")][1]/@href'''):
print(url)

产量

http://www.somewebsite.com

我发现 lxml(和 XPath)是一种表达我正在寻找的元素的便捷方式。但是,如果安装第三方模块不是一个选项,您也可以使用 HTMLParser 完成此特定工作。来自标准库:

import HTMLParser
import contextlib

class MyParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.last_link = None

def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if 'href' in attrs:
self.last_link = attrs['href']

content = '''<html><a href="http://www.not-this-one.com"></a>
<a href="http://www.somewebsite.com"></a><p>other stuff</p><p>sales</p>
</html>
'''

idx = content.find('sales')

with contextlib.closing(MyParser()) as parser:
parser.feed(content[:idx])
print(parser.last_link)

关于lxml方案中使用的XPath: XPath含义如下:

 //*                              # Find all elements
[contains(text(),"sales")] # whose text content contains "sales"
/preceding::* # search the preceding elements
[starts-with(@href,"http")] # such that it has an href attribute that starts with "http"
[1] # select the first such <a> tag only
/@href # return the value of the href attribute

关于python - 使用正则表达式搜索关键字附近的 HTML 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8966244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com