如何用python从网站中提取传出链接?

2024-09-29 18:36:09 发布

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

def parsehttp(url):
    r = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(r, 'lxml')


    for link in soup.find_all('a'):
        href = link.attrs.get("href")
        print(href)

我想能够提取所有传出链接从一个网站,然而,我现在的代码是返回两个相对链接和传出链接,我只希望传出链接。区别在于传出链接中包含https部分,而相对链接则不包含https部分。我还想获得的'标题'部分,每个链接以及


Tags: httpsurlforread链接requestdeflink
3条回答

您可以检查href的前5个字符是否为https来标识:

if href[0:5] == "https":
   #outgoing link
else:
   #incoming link
for link in soup.find_all('a'):
    href = link.attrs.get("href", "")
    if not href.startwith("https://"):
        continue
    
    print(href) 

可以使用正则表达式:

for link in soup.findAll('a', attrs={'href': re.compile("^(http|https)://")}):
    href = link.attrs.get("href")
    if href is not None:
        print(href)

相关问题 更多 >

    热门问题