簡體   English   中英

Python Re.Search:如何在兩個字符串之間找到 substring,該字符串還必須包含特定的 substring

[英]Python Re.Search: How to find a substring between two strings, that must also contain a specific substring

我正在編寫一個小腳本來從基本的 HTML 頁面獲取我的 F@H 用戶數據。

我想在該頁面上找到我的用戶名以及它之前和之后的數字。

我想要的所有數據都在兩個 HTML <tr></tr>標簽之間。

我目前正在使用這個:

re.search(r'<tr>(.*?)</tr>', htmlstring)

我知道這適用於任何 substring,因為我的問題的所有谷歌結果都顯示。 這里的區別是我只需要它 substring 也包含一個特定的詞

但是,這只返回這兩個分隔符之間的第一個字符串,甚至不是全部。

這種模式在頁面上出現了數百次。 我懷疑它並沒有全部得到它們,因為我沒有正確處理所有換行符,但我不確定。

如果它會返回所有這些,我至少可以將它們整理出來,找到一個包含我的用戶名通過每個result.group()的用戶名,但我什至不能這樣做。

多年來,我一直在擺弄不同的正則表達式,但無法弄清楚我需要什么,我感到非常沮喪。

TL;DR - 我需要一個re.search()模式,它可以在兩個單詞之間找到一個 substring,它還包含一個特定的單詞。

如果我理解正確,這樣的事情可能會奏效
<tr>(?:(?:(?:(?.<\/tr>)?)*?)\bWORD\b(:.?*?))<\/tr>

  • <tr>找到“<tr>”
  • (?:(?:(?.<\/tr>)?)*?)盡可能少地查找除 "</tr>" 之外的任何內容
  • \bWORD\b查找 WORD
  • (?:.*?))盡可能少地找到任何東西
  • <\/tr>找到“</tr>”

樣本

有幾種方法可以做到,但我更喜歡 pandas 方式:


from urllib import request

import pandas as pd # you need to install pandas

base_url = 'https://apps.foldingathome.org/teamstats/team3446.html'

web_request = request.urlopen(url=base_url).read()

web_df: pd.DataFrame = pd.read_html(web_request, attrs={'class': 'members'})
web_df = web_df[0].set_index(keys=['Name'])
# print(web_df)

user_name_to_find_in_table = 'SteveMoody'
user_name_df = web_df.loc[user_name_to_find_in_table]
print(user_name_df)

然后有很多方法可以做到這一點。 僅使用 Beautifulsoup 查找或 css 選擇器,或者可能像彼得建議的那樣重新使用?

使用 beautifulsoup 和“查找”方法,然后重新,您可以通過以下方式進行操作:

import re
from bs4 import BeautifulSoup as bs # you need to install beautifullsoup
from urllib import request




base_url = 'https://apps.foldingathome.org/teamstats/team3446.html'

web_request = request.urlopen(url=base_url).read()

page_soup = bs(web_request, 'lxml') # need to install lxml and bs4(beautifulsoup for Python 3+)

user_name_to_find_in_table = 'SteveMoody'

row_tag = page_soup.find(
    lambda t: t.name == "td"
              and re.findall(user_name_to_find_in_table, t.text, flags=re.I)
).find_parent(name="tr")

print(row_tag.get_text().strip('tr'))

使用 Beautifulsoup 和 CSS 選擇器(沒有重新但 Beautifulsoup):

from bs4 import BeautifulSoup as bs # you need to install beautifulsoup
from urllib import request


base_url = 'https://apps.foldingathome.org/teamstats/team3446.html'

web_request = request.urlopen(url=base_url).read()

page_soup = bs(web_request, 'lxml') # need to install lxml and bs4(beautifulsoup for Python 3+)

user_name_to_find_in_table = 'SteveMoody'

row_tag = page_soup.select_one(f'tr:has(> td:contains({user_name_to_find_in_table})) ')

print(row_tag.get_text().strip('tr'))

在您的情況下,我更喜歡 pandas 示例,因為您保留標題並且可以輕松獲取其他統計信息,並且它運行得非常快。

使用回復:

到目前為止,最好的輸入是 Peters 的評論Link ,所以我只是將它改編為 Python 代碼(很高興得到編輯),因為這個解決方案不需要任何額外的庫安裝。

import re
from urllib import request




base_url = 'https://apps.foldingathome.org/teamstats/team3446.html'

web_request = request.urlopen(url=base_url).read()
user_name_to_find_in_table = 'SteveMoody'
re_patern = rf'<tr>(?:(?:(?:(?!<\/tr>).)*?)\{user_name_to_find_in_table}\b(?:.*?))<\/tr>'
res = re.search(pattern=re_patern, string= str(web_request))

print(res.group(0))


有用的 lin 在正則表達式中使用變量: stackflow

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM