【发布时间】:2017-07-16 19:04:18
【问题描述】:
根据 Ryan Mitchell 的《Web Scraping with Python》一书, 他使用重新编译。任何人都可以解释一下 re.compile() 在这种情况下的用途,以及 re.compile() 中的内容
代码是用 python 3 编写的
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen("http://en.wikipedia.org"+pageUrl)
bsObj = BeautifulSoup(html)
for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
if 'href' in link.attrs:
if link.attrs['href'] not in pages:
#We have encountered a new page
newPage = link.attrs['href']
print(newPage)
pages.add(newPage)
getLinks(newPage)
getLinks("")
【问题讨论】:
标签: python regex python-3.x web-scraping beautifulsoup