2 xuezha009 xuezha009 于 2018.01.12 19:43 提问

爬虫遇到一个小问题 请大佬们帮帮忙 5C

图片说明我想爬小猪租房网北京地区房源前三页 我的爬虫书上用开发者工具的copyselector 爬取
请问为什么 我的代码运行不对 什么也不显示 我是大一学生不懂什么具体的html css具体规则
基本点完copyselector 就直接粘贴了 不知道是否还要加工一下图片说明

 #encoding:utf-8
from bs4 import BeautifulSoup
import requests
import time

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'}


def get_links(url):
    wbdata = requests.get(url, headers=headers)
    print(wbdata.status_code)
    soup = BeautifulSoup(wbdata.text, 'lxml')
    links = soup.select('#page_list > ul > li > a')
    for link in links:
        href = link.get("href")
        get_info(href)


def get_info(url):

    wbdata = requests.get(url, headers=headers)
    soup = BeautifulSoup(wbdata.text, 'lxml')
    tittles = soup.select('div.pho_info > h4')
    addresss = soup.select('body > div.wrap.clearfix.con_bg > div.con_l > div.pho_info > p > span')
    prices = soup.select('#pricePart > div.day_l > span')
    for tittle, address, price in zip(tittles, addresss, prices):
        data={'tittle':tittle.get_text().strip(),'address':address.get_text().strip(),'price':price.get_text()}
        print(data)

if __name__ == '__main__':
    urls = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(number) for number in range(1, 3)]
    for ursl in urls:
        get_links(ursl)
        time.sleep(2)

1个回答

lifeifei1245
lifeifei1245   2018.01.12 20:08

我看了一下,是你的address css错误 ,导致zip(tittles, addresss, prices) 出的结果永远都是空的,不会进入打印的那一步

addresss = soup.select('div.con_l > div.pho_info > p > span') 将css的一行改为这个,再试一下吧

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!