from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import random
base_url = "https://baike.baidu.com"
#导入相关的包html
his = ["/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711"]
#初始化url
#循环选取20百度百科的数据
for i in range(20):
url = base_url + his[-1]
#组合url
html = urlopen(url).read().decode('utf-8')
#获取网页内容
soup = BeautifulSoup(html, features='lxml')
#beautifulsoup经过lxml显示解析网页正则表达式
print(i, soup.find('h1').get_text(), ' url: ', base_url+his[-1]) #将如下信息打印出来 sub_urls = soup.find_all("a", {"target": "_blank", "href": re.compile("/item/(%.{2})+$")}) #经过正则表达式,首先找到a标签,而后选取含有target的内容,而且href 她的必须匹配以/item/开头的形式 if len(sub_urls) != 0: his.append(random.sample(sub_urls, 1)[0]['href']) #经过random的sample方法从sub-url中水机选去一个长度为一的list的a标签,而后选区他的href属性 else: # no valid sub link found his.pop() #若是当前没有连接,退出再来,而后再选择一个,在来 