標籤:python爬蟲;人工智慧
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import random
base_url = "https://baike.baidu.com"
#匯入相關的包
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})+$")})#通過Regex,首先找到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() #如果當前沒有連結,退出再來,然後再選擇一個,在來 
最最簡單的python爬蟲教程--爬取百度百科案例