从入门到入狱------从入门到入狱-----做爬虫之前的准备(bs4的使用方法和应用)


from bs4 import BeautifulSoup
import requests
import re
# html页面解析的方法
'''
正则表达式  ---- 不懂前端,正则用得好 (re模块)
通过css选择器选中标签 ----熟悉css选择器;熟悉jQuery  (bs4库和pyQuery)
通过xPath获取标签 ---- 熟悉html结构和标签(lxml)
'''


# bs4的使用
# 网页内容---html格式的字符串,一般使用requests或者selenium获取

# 打开安居客的新房网页
def get_data():
    with open('spider.html', 'r', encoding='utf-8') as f:
        return f.read()


print(get_data())
# 根据网页内容创建解析器对象
# soup=BeautifulSoup(网页内容,解析器类型)

soup = BeautifulSoup(get_data(), 'lxml')
# 根据标签属性获取
'''
bs4对象.select(css选择器)---获取选择器选中所有的标签
bs4对象.select_one(css选择器)---获取选择器选中的第一个标签
'''
# 获取房屋名字 contents
house_name = soup.select('.items-name')
print(house_name)
for i in house_name:
    print(i.contents)

house_details = soup.select('.tags-wrap')
for i in house_details:
    print(i.attrs['href'])
#获取价格内容 .get_text()
house_prices = soup.select('.price')
for i in house_prices:
    print(i.get_text())  # 最低10842元/㎡起
# 获取图片内容 .attrs[属性名]
imgs=soup.select('.pic>img')
for i in imgs:
    print(i.attrs['src'])

print('-'*20)
# 根据标签内容获取 解析器对象.find_all
# find_all(attrs{'属性1':'属性值1','属性2':'属性值2'})-获取属性1是属性值1并且属性2是属性值2的标签内容
# 获取房屋价格信息

house_price = soup.find_all(attrs={'class':'price'})
print(house_price)

小试牛刀:爬取楼盘信息,没有注释哟,代码结合上文所讲就能懂了

from bs4 import BeautifulSoup

def get_data():
    with open('spider.html', 'r', encoding='utf-8') as f:
        return f.read()

def hous_data():
    soup=BeautifulSoup(get_data(),'lxml')

    # 获取所有楼盘对应的div
    huos_box=soup.select('.list-results .item-mod')
    print(huos_box)
    for _ in huos_box:
        print('-'*30)
        x=_.select_one('.price')
        i=_.select_one('.items-name')
        house={
            'name':i.get_text(),'price':x.get_text() if x else None
        }
        print(house)



hous_data()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值