通過request擷取網頁資訊 通過BeautifulSoup剖析網頁元素

來源:互聯網
上載者:User

標籤:from   request   get   sel   href   other   int   擷取網頁   text   

import  requestsnewsUrl =‘http://news.sina.com.cn/china/‘res = requests.get(newsUrl)res.encoding =‘utf-8’pintprint(res.text)//然後通過DOM Tree來剖析網頁元素   from bs4 import BeautifulSouphtml_sample =‘\<html>\<body>\<h1 id="title">this is h1</h1>\<a class="link" href="fdfdfdfd">this is a link</a>\<a class="link" href="fdfdfdfd">this is another link</a>\</body>\</html>‘‘‘‘html.parser  解析器 ,不寫的話會發出警告‘‘‘soup = BeautifulSoup(html_sample,‘html.parser’)print(soup.text)#找出所有含特定標籤的HTML元素 #1: 使用select 找出含有h1標籤的元素header = soup.select(‘h1’)print(header)print(header[0].text ) #第0個標籤中的文字 #2: 使用select找出含有a標籤的元素alink = soup.select(‘a’)print(alink)for link in alink:#print(link)print(link.text)#取得含有特定CSS屬性的元素#1使用select找出所有id為title的元素(id前需加#) aTitle = soup.select(‘#title‘)print(aTitle)#2使用select找出所有class為link的元素(class前需要加.)for mylink in soup.select(‘.link‘):print(mylink)#取得所有a標籤內的連結#使用select找出所有a tag的href連結 ahref = soup.select(‘a‘)for ah in ahref:   print(ah[‘href‘]) 

通過request擷取網頁資訊 通過BeautifulSoup剖析網頁元素

聯繫我們

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