python3 [爬蟲實戰] selenium + requests 爬取安居客

很簡單,這里是根據網友的求助爬取的安居客上的一個頁面的全部地區名稱跟鏈接

因為她用的scrapy框架,感覺有些大才小用了,所以就直接用了一個requests庫,selenium 和xpath進行一整頁數據的爬取

我們爬取的網站:https://www.anjuke.com/sy-city.html

獲取的內容:包括地區名,地區鏈接:

安居客詳情

1 一開始直接用requests庫進行網站的爬取,會訪問不到數據的, 會直接出現 訪問的頁面出現錯誤的信息。(ps:這里就暫時不打印出來了。)

2 因為一直報錯,腦瓜子不知道怎么的就想到了selenium 這個框架,可能是爬安居客之前用selenium 爬取了天貓的商品內容吧。

3 selenium 的使用,我的博客上有說過:

http:/blog.csdn.net/xudailong_blog/

4 現在貼上代碼片段:

# -*- 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'.*?<a href="(.*?)</a>'
    reg_author = re.compile(regAuthor)
    authorother = re.findall(reg_author, html)

    global num0
    nums = 0

    for info in authorother:
        verinfo = info.split('">')
        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)

當然,文本存儲還有一些瑕疵,因為用的是正則表達式,并沒有進行很嚴格的匹配

貼上爬取圖片:

安居客爬取圖片

正確的數據 650條左右,因為問了一下給需求的小姐姐,說是可以,所以就這樣子處理了。

代碼就是上面那些,以后有同樣入門的一塊學習的小伙伴或者需要幫忙爬蟲的,可以私信我,我可以試著去爬一下,因為自己也是自學3個月左右。代碼有放到GitHub上了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容