- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
如果我正在寻找关键字“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/
我的子查询给出了一个错误:Msg 102, Level 15, State 1, Line 17 Incorrect syntax near ')'. SELECT SalesArea, Branch
当我尝试运行此查询时: select branch_no, max (avg_salary) from (select allocatedto, avg (salary) from sta
所以我正在更新 phpmyadmin 中的表。数据在里面,列已成功创建。当我尝试使用下面的代码添加图像时,出现此错误 Unexpected character. (near "\" at positi
我正在尝试在 phpMyAdmin 中执行以下查询,但出现错误。我已经查看过类似的问题,但我仍然无法弄清楚为什么它不起作用。 INSERT INTO discussion_forum (event_t
我正在用 C 构建一个 client-server socket 模拟 我接受来自客户端的 TCP 连接 然后客户端发送消息到我的服务器。我已成功收到消息,然后遍历 structs 的 array 以
我在 AUTOINCREMENT 附近遇到语法错误。这个错误的原因是什么? CREATE TABLE person ( id INTEGER NOT NULL AUTOINCREMENT,
当我尝试使用 java 在 SQLite 中以编程方式创建数据库时,它会在控制台中生成以下错误。 java.sql.SQLException: near "DATABASE": syntax erro
我似乎无法弄清楚出了什么问题。我尝试查询的子部分,但仍然无法解决问题。 表格格式: poi(id int, minX float, minY float, maxX float, maxY float
我在VHDL中编写了以下代码: library IEEE ; use IEEE.STD_LOGIC_1164.all ; entity encoder is port( x : in std_
我在我的游戏服务器中使用这些文件,每次我添加一个新的玩家模型时,我都会得到 [ERROR] lua/autorun/server/fastdlskins.lua:938: '' expected ne
我正在尝试更新我的 sqlite3 数据库,但出现此错误。我能够成功地将数据插入同一数据库,但无法更新它。请帮忙。 [SQLITE_ERROR] SQL error or missing databa
我想在通知区域旁边显示一个小弹出窗口。它类似于 Outlook/Skype/Live! Messenger/etc 在显示有关新消息的通知时会执行此操作。在我的例子中,它将有一些输入控件(文本框、日期
我正在尝试编写简单的程序以使用 gorp 将行插入表中,但在创建表时出现错误。 代码如下: package main import _ "github.com/mattn/go-sqlite3" im
我正在尝试运行工作目录中的 Octave 文件,但出现错误。 Octave 似乎没有认识到它应该运行该文件。 unknown@unknown> dir .
我正在尝试编写一些代码来模拟具有两个三态缓冲器和VHDL中的上拉电阻的电路。下面是我的代码: library ieee; use ieee.std_logic_1164.all; entity Pul
你能好心告诉我这里出了什么问题吗? conn 是 DriverManager.getConnection(DB_URL) try { PreparedState
我想在go中创建一个事务,同时这样做会出现错误:near "SET": syntax error。代码: db.Exec("SET TRANSACTION ISOLATION LEVEL REPEAT
所以我想用这样的颜色可视化一个矩阵 library(RColorBrewer) vec = rbinom(10000,1,0.1) n = sum(vec) vec = ifelse(vec == 1
private static final String QUERY = "SELECT * FROM " + TABLE_SONG_DETAILS + " WHERE " + TABLE_SONG_D
希望大家一切都好。 我正在尝试创建一个 mysql 触发器,但是我不断收到以下错误: [Err] 1064 - You have an error in your SQL syntax; check
我是一名优秀的程序员,十分优秀!