正则表达式未返回完整结果

时间:2019-06-03 20:04:57

标签: python regex beautifulsoup python-requests

我有一个正则表达式,它试图匹配HTML中的href属性。 Href在脚本标签和函数之间。我认为我使用了正确的正则表达式,但是结果不完整,将其切成两半。

我已经在多个Python Regex测试站点上尝试过该正则表达式,并且都给出了正确的结果,但是在我自己的脚本中尝试时,它给出的结果未完成。

def gotoDownload(link):
    try:
        with requests.Session().get(link) as download:
            if isUrlOnline(download):
                soup = BeautifulSoup(download.content, 'html.parser')
                filtered = soup.find_all('script')
                print(re.search(r"\'http[\s=[\s\"\']*(.*?)[\"\']*.*?\'", filtered[17].text))

链接的预期结果应为: 'http://mediafile.cloud/b34b4f6720a31f73?pt=UkhBMmVHczFaRXA2Uld4ek1qYzVWME5DYzNodVFUMDlPampsTkQ5aFNpVWxQamVlZ3REQkpEdz0%3D'

但是输出是: match =“'http://mediafile.cloud/b34b4f6720a31f73?pt=UkhBM

它被切成两半,出于某种原因在= UkhBM之后结束。

2 个答案:

答案 0 :(得分:0)

如果我们只想获取任何具有'http'的URL,我们将以一个简单的表达式开始,例如:

('http.*?')

Demo

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"('http.*?')"

test_str = ("'http://mediafile.cloud/b34b4f6720a31f73?pt=UkhBMmVHczFaRXA2Uld4ek1qYzVWME5DYzNodVFUMDlPampsTkQ5aFNpVWxQamVlZ3REQkpEdz0%3D'\n"
    "'https://mediafile.cloud/b34b4f6720a31f73?pt=UkhBMmVHczFaRXA2Uld4ek1qYzVWME5DYzNodVFUMDlPampsTkQ5aFNpVWxQamVlZ3REQkpEdz0%3D'\n"
    "'http://www.mediafile.cloud/b34b4f6720a31f73?pt=UkhBMmVHczFaRXA2Uld4ek1qYzVWME5DYzNodVFUMDlPampsTkQ5aFNpVWxQamVlZ3REQkpEdz0%3D'\n"
    "'https://www.mediafile.cloud/b34b4f6720a31f73?pt=UkhBMmVHczFaRXA2Uld4ek1qYzVWME5DYzNodVFUMDlPampsTkQ5aFNpVWxQamVlZ3REQkpEdz0%3D'")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx电路

jex.im可视化正则表达式:

enter image description here

答案 1 :(得分:0)

出于某些原因更改

re.match(r"('http.*?')", filtered[17].text

re.findall(r"('http.*?')", filtered[17].text

有效:-O