问题描述
要爬虫wiki内容描述页的链接,确保这些链接指向新的内容页,为此利用正则表达式,代码如下:
# webCrawler.py
# date: 2020-08-15
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
# Because Wikipedia cann't be open, we use the following website
# alternatives.
html = urlopen('https://encyclopedia.thefreedictionary.com/Kevin+Bacon')
bs = BeautifulSoup(html, 'html.parser')
for link in bs.find_all('a',href=re.compile('((?!\.).)*\+.*')):
if 'href' in link.attrs:
print(link['href'])
可运行的结果为:
结果中仍然有//起头的超链接。上述代码中(?!\.)
即是不想让在链接中出现“.”,可是还是出现了。
解决方案
我是自己摸索的,将正则表达式改为:
re.compile('^((?!\.).)*\+.*$'))
即可得到正确结果,亦即将//起头的结果过滤掉了。
疑问
谁能告诉我为什么?