前言
上一篇中我们在维基百科的内部网站上随机跳转进入文章类网页,而忽视外部网站链接。本篇文章将处理网站的外部链接并试图收集一些网站数据。和单个域名网站爬取不同,不同域名的网站结构千差万别,这就意味我们的代码需要更加的灵活以适应不同的网站结构。
因此,我们将代码写成一组函数,这些函数组合起来就可以应用在不同类型的网络爬虫需求。
随机跳转外部链接
利用函数组,我们可以在50行左右满足爬取外部网站的需求。
示例代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import datetime
import random
from urllib.parse import quote
pages = set()
random.seed(datetime.datetime.now())
''' 获取一个网页的所有互联网链接'''
# 获取网页所有内部链接
def get_internal_links(soup, include_url):
internal_links = []
# find all links that befin with a '/'
print(include_url)
for link in soup.find_all('a',
href=re.compile(r'^((/|.)*' + include_url + ')')):
if link.attrs['href'] is not None:
if link.attrs['href'] not in internal_links:
internal_links.append(link.attrs['href'])
return internal_links
# retrieves a list of all external links found on a page
#获取网页上所有外部链接
def get_external_links(soup, exclude_url):
external_links = []
# Finds all links that starts with 'http' or 'www' that do not contain the
# current URL
for link in soup.find_all('a',
href=re.compile(r'^(http|www)((?!' + exclude_url + ').)*$')):
if link.attrs['href'] is not None:
if link.attrs['href'] not in external_links: