最基礎網頁爬蟲

來源:互聯網
上載者:User

標籤:link   cal   基礎   imp   headers   2.0   code   lxml   模組   

第一個網頁文本爬蟲程式(沒有添加下載器):

 1 import requests 2 from bs4 import BeautifulSoup 3 import os 4  5 headers={‘User-Agent‘:"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTMl,like Gecko) Chrome/22.0.1207.1 Safari/537.1"} 6 url_begin= ‘http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000‘ 7 start_url=requests.get(url_begin,headers=headers) 8 #print(start_url.text) 9 Soup=BeautifulSoup(start_url.text,‘lxml‘)10 link_list=Soup.find(‘div‘,class_="x-sidebar-left-content").find_all(‘a‘)11 #print(link_list)12 13 for link in link_list:14         url=‘http://www.liaoxuefeng.com‘ + link[‘href‘]15         html=requests.get(url,headers=headers)16         html_Soup=BeautifulSoup(html.text,‘lxml‘)17         title_list = html_Soup.find(‘div‘, class_="x-content").find_all(‘h4‘)18         # print(title_list)19         for title in title_list:20             titlereal = title.get_text()21             print(titlereal)22 23         content_list = html_Soup.find("div", class_="x-wiki-content").find_all(‘p‘)24         for content in content_list:25             # print(content)26             contentreal = content.get_text()27             print(contentreal)

 

 

 

 

第二個網頁圖片爬蟲(引入os模組,可以將網頁內容爬取到本地檔案夾)

 1 import requests 2 from bs4 import BeautifulSoup 3 import os 4 import urllib 5 import urllib3 6  7 url= ‘http://www.dbmeinv.com/?pager_oofset=1‘ 8 x=0 9 10 def crawl(url):11     headers = {12         ‘User-Agent‘: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTMl,like Gecko) Chrome/22.0.1207.1 Safari/537.1"}13     req=requests.get(url,headers=headers)14 15     Soup=BeautifulSoup(req.text,‘lxml‘)16     link_list=Soup.find_all(‘img‘)17     for girl in link_list:18         link= girl.get(‘src‘)19         print(link)20 21         global x22         path=r‘/Users/wangxitao/Desktop/douban‘23         local=os.path.join(path,‘image\%s.jpg‘%x)24         urllib.request.urlretrieve(link,local)25                                          #‘image\%s.jpg‘%x26 27         x+=128         print("正在下載第%s張"%x)29 30 for page in range(1,10):31     page+=132     url=‘http://www.dbmeinv.com/?pager_offset=%d‘%page33     crawl(url)34 35 print(‘爬取完畢‘)

 

最基礎網頁爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.