Python中两个不同的<class>上的正则表达式

2024-09-30 10:35:08 发布

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

环顾四周后,我找不到任何与我的问题相符的答案

事实上,我解析了一个url并获取了源代码,然后我想制作一个日期列表,但是这些日期在两个不同的<class>

如果我这样做:

pattern='<h5 class="preparation|soutenue">(.+?(?=</h5>))'

它将只返回<class="soutenue">的内容和<class="preparation">的空值

*我尝试了许多其他模式,但它们总是返回空列表

如果有人能帮忙,我将不胜感激

如果您想试用,下面是完整的代码:Python 3.8

# coding: utf8
import requests
import re
import pdb
from os import getcwd #getcwd() donne le repertoire courant ou se situe le script
from os.path import *
import os

#PARSING

#Var chemin du dossier "pages"
test_dossier = (getcwd()+"\\pages")

#Boucle pour parser les 6 pages
x=0
while x<=50:
url= 'http://theses.fr/fr/?q=crypto%20monnaies&start='+str(x)
request_headers={'User-Agent': "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6" }

req=requests.get(url,headers=request_headers,timeout=10)
content=req.text
#Verification que le dossier existe sinon le crée
if exists(test_dossier):
    with open('pages/theses'+str(x)+'.txt','w', encoding='utf8') as output:
        output.write(content)
else : 
    os.mkdir(test_dossier)
    with open('pages/theses'+str(x)+'.txt','w', encoding='utf8') as output:
        output.write(content)
x+=10

print("Parsing ok !")

#GET DATAS
tab_dates=[]

for j in range(0,51,10):
    with open('pages/theses'+str(j)+'.txt', 'r',encoding='utf8') as output:
        contenu=output.read()

    pattern='<h5 class="preparation|soutenue">(.+?(?=</h5>))'

    result=re.findall(pattern, contenu)
    tab_dates.append(result)

print(tab_dates)
print("datas ok !")

Tags: importleurloutputospagesutf8class

热门问题