python网络爬虫实战笔记(一)

来源:互联网 发布:seo必备工具 编辑:程序博客网 时间:2024/05/16 23:48
# -*- coding: utf-8 -*-"""Spyder EditorThis is a temporary script file."""import requestsres = requests.get('http://news.sina.com.cn/china/')res.encoding = 'utf-8'#print(res.text)from bs4 import BeautifulSouphtml_sample = '\<html> \<body> \<h1 id ="title">Hello World</h1> \<a href="#" class="link">This is link1</a> \</body> \<html>'soup = BeautifulSoup(html_sample,'html.parser')print(soup.text)#使用select找出含有h1标签的元素soup = BeautifulSoup(html_sample,'html.parser')header = soup.select('h1')print(header)# 如果要把里面的元素取出来加中括号0print(header[0])# 如果仅要文字print(header[0].text)# 使用select找出含有a标签的元素soup = BeautifulSoup(html_sample,'html.parser')alink = soup.select('a')print(alink)#里面包含两个元素for link in alink:#把两个元素分别在两行打印出print(link)#仅取出文字print(link.text)# 取得含有特定css属性的元素# 使用select找出所有id为title的元素(id前面需加#)alink = soup.select('#title')print(alink)#使用select找出所有class为link的元素(class前面需要加.)for link in soup.select('.link'):print(link)# 取得所有a标签内的链接#使用select找出所有a tag的href连结alinks = soup.select('a')for link in alinks:print(link)print(link['href'])


原创粉丝点击