最最簡單的python爬蟲教程--爬取百度百科案例

來源:互聯網
上載者:User

標籤: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()    #如果當前沒有連結,退出再來,然後再選擇一個,在來            ![](http://i2.51cto.com/images/blog/201803/27/2ec8773ff147c38305ae581297c51351.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

最最簡單的python爬蟲教程--爬取百度百科案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.