python – 使用Regex搜索关键字附近的HTML链接
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用Regex搜索关键字附近的HTML链接,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1846字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用Regex搜索关键字附近的HTML链接](/upload/InfoBanner/zyjiaocheng/776/7bf0d28be3684b3e9f7bd5444d56b41f.jpg)
如果我正在寻找关键字“sales”,即使文件中有多个链接,我也希望得到最近的“http://www.somewebsite.com”.我想最近的链接不是第一个链接.这意味着我需要搜索关键字匹配之前的链接.
这不起作用……
regex =(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 – 使用Regex搜索关键字附近的HTML链接全部内容,希望文章能够帮你解决python – 使用Regex搜索关键字附近的HTML链接所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。