从源代码中提取带有regex的链接;Python

2024-09-28 17:03:36 发布

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

我有一个数据集的链接到报纸文章,我想做一些研究。但是,数据集中的链接以.ece扩展名结尾(这对我来说是个问题,因为有些api限制)

http://www.telegraaf.nl/telesport/voetbal/buitenlands/article22178882.ece

以及

http://www.telegraaf.nl/telesport/voetbal/buitenlands/22178882/__Wenger_vreest_het_ergste__.html

是指向同一页的链接。 现在我需要将所有.ece链接转换为.html链接。我没有找到一个更简单的方法来做这件事,而是解析页面并找到原始的.html链接。问题是链接隐藏在html元元素中,我无法使用树.xpath. 你知道吗

<meta content="http://www.telegraaf.nl/telesport/voetbal/buitenlands/22178882/__Wenger_vreest_het_ergste__.html"

不幸的是,我不太熟悉regex,也不知道如何使用它提取链接。 基本上,我需要的每一个链接都将从以下内容开始:

<meta content="http://www.telegraaf.nl/

我需要完整的链接(即http://www.telegraaf.nl/THE_REST_OF_THE_LINK)。 另外,我使用BeautifulSoup进行解析。谢谢。你知道吗


Tags: 数据http链接htmlwwwnlhetece
3条回答

使用BeautifulSoup查找匹配的内容属性,然后将其替换为:

from bs4 import BeautifulSoup
import re

html = """
    <meta content="http://www.telegraaf.nl/telesport/voetbal/buitenlands/article22178882.ece" />
    <meta content="http://www.telegraaf.nl/telesport/voetbal/buitenlands/22178882/__Wenger_vreest_het_ergste__.html" />
"""

soup = BeautifulSoup(html)
# reference table of url prefixes to full html link
html_links = {
    el['content'].rpartition('/')[0]: el['content'] 
    for el in soup.find_all('meta', content=re.compile('.html$'))
}
# find all ece links, strip the end of to match links, then adjust
# meta content with looked up element
for el in soup.find_all('meta', content=re.compile('.ece$')):
    url = re.sub('(?:article(\d+).ece$)', r'\1', el['content'])
    el['content'] = html_links[url]

print soup
# <meta content="http://www.telegraaf.nl/telesport/voetbal/buitenlands/22178882/__Wenger_vreest_het_ergste__.html"/>
(.*?)(http:\/\/.*\/.*?\.)(ece)

试试看这个。换掉通过$2html。你知道吗

请参见演示。你知道吗

http://regex101.com/r/nA6hN9/24

这里有一个非常简单的正则表达式让你开始。你知道吗

This one将提取所有链接

\<meta content="(http:\/\/www\.telegraaf\.nl.*)"

这个将匹配所有的html链接

\<meta content="(http:\/\/www\.telegraaf\.nl.*\.html)"

要将其与您所拥有的一起使用,您可以执行以下操作:

import urllib2
import re

replacements = dict()
for url in ece_url_list:
    response = urllib2.urlopen(url)
    html = response.read()
    replacements[url] = re.findall('\<meta content="(http:\/\/www\.telegraaf\.nl.*\.html)"', html)[0]

注意:这假设每个源代码页在这个meta标记中总是包含一个html链接。它只期望一个。你知道吗

相关问题 更多 >