用于捕获元素textConten的正则表达式

2024-06-16 08:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

只是想从一个网站上抓取事件的标题,我有他们的大部分,但它不会拿起一个标题。缺少的结果是:

AFL U16’s Championships

有人能告诉我需要在正则表达式中更改什么才能找到这个吗?你知道吗

from re import *
from urllib.request import urlopen

Website = 'https://thegabba.com.au/what-s-on.aspx'
print('Now Gathering Results from URL: ' + Website)

html_source = urlopen(Website).read().decode("UTF-8")
EventMatches = findall('<h6 class="event-title">([A-Za-z0-9\'\\s]+)</h6>',html_source)

print('There are ' + str(len(EventMatches)) + ' Events.')

for EventNames in EventMatches:
    print(EventNames)

Tags: fromimport标题source网站html事件website
3条回答

撇号与单引号'不同。如果你想把结果包括在内,你需要考虑到前者和后者。你知道吗

内容实际上返回的是二进制而不是utf-8/ascii,因此被解码为iso-8895-1

#!/usr/bin/python3
import re
import requests

Website = 'https://thegabba.com.au/what-s-on.aspx'
print('Now Gathering Results from URL: {}'.format(Website))

html_source = requests.get(Website).content.decode('ISO-8859-1') 
EventMatches = re.findall(r'<h6 class="event-title">([A-Za-z0-9\'\s]+)<\/h6>', html_source)

print('There are {} Events.'.format(len(EventMatches)))

for EventNames in EventMatches:
    print(EventNames)
Now Gathering Results from URL: https://thegabba.com.au/what-s-on.aspx
There are 14 Events.
Brisbane Lions v Hawthorn Football Club
Brisbane Lions v Melbourne Football Club
Brisbane Lions v North Melbourne Football Club
Stadium Stomp
Brisbane Lions v Western Bulldogs
Brisbane Lions v Gold Coast Suns
Muscle Up For MND
Brisbane Lions v Geelong Football Club
Australia v Sri Lanka
Australia v Pakistan
Pakistan v New Zealand
Australia v A1
New Zealand v A1
England v Afghanistan

我们在这里可能需要的表达是:

<h6 class="event-title">(.+?)<\/h6>

它捕获了h6标记中的所有内容。你知道吗

DEMO

测试

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

import re

regex = r"<h6 class=\"event-title\">(.+?)<\/h6>"

test_str = "<h6 class=\"event-title\">Brisbane Lions v Hawthorn Football Club and Anthing else we wish here including @#$%^&*(</h6>"

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.

enter image description here

正则表达式电路

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

enter image description here

相关问题 更多 >