正则表达式,用于捕获元素textContent

时间:2019-05-25 02:32:36

标签: python regex

只是试图从一个网站上获取事件的标题,而我却拥有大多数,但不会获得一个标题。缺少的结果是:

  

AFL U16锦标赛

有人可以告诉我我需要在正则表达式中进行哪些更改才能找到它吗?

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)

3 个答案:

答案 0 :(得分:3)

撇号与单引号' 不同。如果要包含该结果,则需要考虑前者和后者。

答案 1 :(得分:0)

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

<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

RegEx电路

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

enter image description here

答案 2 :(得分:0)

内容实际上返回的不是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