以爬取房天下的租房信息为例:
需要爬取的字段有,户型,租金,面积,朝向,楼层,装修情况,标签,小区名称,地区
因为这个网站没有反爬虫所以不需要用到代理IP
#导入模块
from bs4 import BeautifulSoup
import requests
def crawlFang(url,data,href): #定义一个爬取字段的函数
res = requests.get(url)
html=res.text #获取网页内容
#获取BeautifulSoup对象
soup=BeautifulSoup(html,'html.parser')
#寻找需要爬取内容的标签
div=soup.find('div',class_="houseList")
divs=div.find_all('dl',class_="list hiddenMap rel")
divs.pop(10) #第十一个标签是广告需要删掉
for each in divs:
#因为户型,朝向,是在一个字段中的,先把整个文本提取出来
text=each.find('dd',class_="info rel").find('p',class_="font15 mt12 bold").get_text().strip().split('|')
#户型
pattern=text[1] #在文本中在