网络爬虫(二):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)
		#转入到该网址

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

猜你喜欢

转载自blog.csdn.net/qq_42785117/article/details/82468054