爬虫基础(三)

案例:

import requests
from bs4 import BeautifulSoup
header = {
    # "Host": 'www.lianjia.com',
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"}

    # User-Agent在f12可以查询 "header"用于伪装python使其看起来像是从浏览器发起的访问

def get_html(url):  # 获取html
    response = requests.get(url,headers=header)
    # 代替了{req = request.Request(url,headers=header)
    #       response = request.urlopen(req)}

    response.encoding = 'utf-8'  # 指定编码
    #代替了 html = response.read().decode() 的编码方式 不过注意该函数返回时为response.text
    
    # print(response.status_code)# 查看 状态码

    if response.status_code == 200:  # 逻辑判断是否返回页面
    # print(response.text)
        return response.text # 即为html
    else:
        print(url)
        return response.status_code


def get_all_url(html): # 获取标签,id,class name等等 从而达到我们提取所需信息的目的
    soup = BeautifulSoup(html,'lxml') # 指定解析方式lxml
    # info clear-- 该网页我们要爬取信息的class
    title = soup.select('div.info.clear div.title a')  # 空格分隔不同标签
    # print(title[0].text)
    all_urls = []
    for i in title:
        all_urls.append(i['href'])  # 也可以get方法获取属性 i.get('href')
    return all_urls

def parser_info(info_html): #传入html,返回打印信息
    soup = BeautifulSoup(info_html,'lxml')
    title = soup.select('.title .main')[0].text #名字】   #  class的并列 用“.加class名”空格分隔
    total = soup.select('span.total')# 售价
    pv = soup.select('.unitPriceValue')# 每平米
    name = soup.select('a.info')# 小区名字
    base = soup.select('.base .content')# 基本属性
    transaction = soup.select('.transaction .content')# 交易属性

# 需要注意的是:select括号中的信息是需要反复尝试才能找到我们真正想要的 可以在网页开发者工具中使用ctrl+f全局搜索
# 看对应条件搜索到的数量是否符合我们的预期

    print(title,
          # total[0].text+"万",
          # pv[0].text,
          # name[0].text,
          str(base[0].text).strip(),
          # transaction[0].text
          )


def save_data(data): # 保存数据(这里不再实现了)
    pass

if __name__ == '__main__':
    url = 'https://bj.lianjia.com/ershoufang/'
    html = get_html(url)
    all_urls = get_all_url(html)
    for url in all_urls:
        info_html = get_html(url)
        parser_info(info_html)



通过f12筛选我们需要的内容
在这里插入图片描述

发布了13 篇原创文章 · 获赞 2 · 访问量 231

猜你喜欢

转载自blog.csdn.net/qq_25871537/article/details/104437260
今日推荐