频道栏目
首页 > 资讯 > Python > 正文

python3使用selenium + requests库爬取安居客

17-09-25        来源:[db:作者]  
收藏   我要投稿

很简单,这里是根据网友的求助爬取的安居客上的一个页面的全部地区名称跟链接

因为她用的scrapy框架,感觉有些大才小用了,所以就直接用了一个requests库,selenium 和xpath进行一整页数据的爬取

获取的内容:包括地区名,地区链接:

安居客详情

1 一开始直接用requests库进行网站的爬取,会访问不到数据的, 会直接出现 访问的页面出现错误的信息。(ps:这里就暂时不打印出来了。)

2 因为一直报错,脑瓜子不知道怎么的就想到了selenium 这个框架,可能是爬安居客之前用selenium 爬取了天猫的商品内容吧。

3 现在贴上代码片段:

# -*- coding: utf-8 -*-
# @Time    : 2017/9/19 21:36
# @Author  : 蛇崽
# @Email   : 17193337679@163.com
# @File    : anjuke.py 安居客房产网
import requests
import re
from bs4 import BeautifulSoup
import csv
import time
import threading
from lxml import etree
from selenium import webdriver
from openpyxl import Workbook

num0 = 1  # 用来计数,计算爬取的书一共有多少本
baseurl = 'https://www.anjuke.com/sy-city.html'

wb = Workbook()
ws = wb.active
ws.title = '安居客'
ws.cell(row=1, column=1).value = '城市名称'
ws.cell(row=1, column=2).value = '城市链接'

def gethtml():
    chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
    browser = webdriver.Chrome(chromedriver)
    browser.get(baseurl)
    time.sleep(5)
    js = 'window.scrollBy(0,3000)'
    browser.execute_script(js)
    js = 'window.scrollBy(0,5000)'
    browser.execute_script(js)
    html = browser.page_source
    return html


def saveinfos(authorother):
    global num0
    nums = 0
    for ver_info in authorother:
        num0 = num0 + 1
        ws.cell(row=num0, column=1).value = ver_info[0]
        ws.cell(row=num0, column=2).value = ver_info[1]
        nums += 1
        print('爬取成功 ' + str(nums))
    wb.save('安居客' + '.xlsx')
    pass


def parseHotBook(html):
    print(html)
    print('*'*20)
    # commentlist = html.xpath("/html/body/div[3]/div")
    regAuthor = r'.*?')
        print(verinfo[0],verinfo[1].replace('class="hot',''))

        num0 = num0 + 1
        name = verinfo[0]
        link = verinfo[1].replace('class="hot','')
        ws.cell(row=num0, column=1).value = name
        ws.cell(row=num0, column=2).value = link
    wb.save('安居客2' + '.xlsx')
    print('爬取成功')
html = gethtml()
parseHotBook(html)

当然,文本存储还有一些瑕疵,因为用的是正则表达式,并没有进行很严格的匹配

贴上爬取图片:

安居客爬取图片

相关TAG标签
上一篇:EXP-00056: 遇到 ORACLE 错误 12154 ORA-12154: TNS: 无法解析指定的连接标识符
下一篇:设计模式动态代理模式
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站