无法从某些相同的链接解析看起来很奇怪的网站地址

时间:2019-08-21 22:13:04

标签: python regex python-3.x web-scraping

我正在尝试从某些相同的网页中获取网站地址。我创建了一个正则表达式来解析相同内容,但是我定义的模式无疑是最糟糕的一种。如何才能从位于p类下post-content标记内的网页中获取网站地址?。

我尝试过:

import re
import requests
from bs4 import BeautifulSoup

links = [
    'https://colegios.es/2012/santisimo-rosario-mosen-rubi-avila/',
    'https://colegios.es/2012/cra-el-valle-villarejo-del-valle/',
    'https://colegios.es/2012/ceip-las-canadas-trescasas/',
    'https://colegios.es/2012/cra-el-barranco-san-esteban-del-valle/'
]

def get_website(link):
    res = requests.get(link,headers={'User-Agent':'Mozilla/5.0'})
    soup = BeautifulSoup(res.text,"html5lib")
    text = soup.select_one('.post-content > p').get_text(strip=True, separator='\n')
    website = re.findall(r'\s+(.*)\n\[', text)[0]
    print(website)

if __name__ == '__main__':
    for link in links:
        get_website(link)

我得到的结果:

www3.planalfa.es/stmorosario
centros1.pntic.mec.es/elvalle/webCra
Dirección: Las Pozas, 17 40194 Trescasas Segovia
Tel. 920 383 556 05005887@educa.jcyl.es   centros1.pntic.mec.es/cp.el.barranco

所需结果:

www3.planalfa.es/stmorosario
centros1.pntic.mec.es/elvalle/webCra

centros1.pntic.mec.es/cp.el.barranco

1 个答案:

答案 0 :(得分:0)

我敢肯定,很快就能打破以下条件

popUpTo