网络爬虫(二):BeautifulSoup的使用

Beautiful Soup 是用 Python 所写的一个 HTML/XML 的解析器
用法
1.导入模块:

import requests
from bs4 import BeautifulSoup

注:这里的bs4是Beautiful Soup +版本号 的缩写

2.获取网站信息

req = requests.get(url)
html=req.text
soup = BeautifulSoup(html,'lxml')

注:这里的lxml是一个十分强大的解析库

3.利用css选择器得到信息

css选择器:要使用css对HTML页面中的元素实现一对一,一对多或者多对一的控制,这就需要用到CSS选择器。HTML页面中的元素就是通过CSS选择器进行控制的。

css选择器参考手册:http://www.w3school.com.cn/cssref/css_selectors.asp


import requests
from bs4 import BeautifulSoup

def detail_page(url):
	req = requests.get(url)	
	html = req.text
	soup = BeautifulSoup(html , 'lxml')
	jod_name = soup.select('.new_job_name')[0].string
	#获得该网站中class属性为new_job_name的内容,其中的[0]是得到第一个
	job_position=soup.select('.job_position')[0].string	
	com_position=soup.select('.com_position')[0].string
	job_detail=soup.select('.job_detail')[1].string
	print('公司项目:{} 地点:{} 公司地址:{}'.format(jod_name,job_position,com_position))
for page in range (2,10):
	req = requests.get('https://www.shixiseng.com/interns/c-None_?k=IT%E4%BA%92%E8%81%94%E7%BD%91&p={}'.format(page)) 
	html=req.text
	soup = BeautifulSoup(html,'lxml')
	for job in soup.select('a.name'):
		url = job.get('href')
		detail_page('https://www.shixiseng.com'+ url)
		#转入到该网址

这样的一个程序就可以抓取实习僧网站的公司项目,地点,公司地址等数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值