很簡單阵难,這里是根據(jù)網(wǎng)友的求助爬取的安居客上的一個(gè)頁面的全部地區(qū)名稱跟鏈接
因?yàn)樗玫膕crapy框架岳枷,感覺有些大才小用了,所以就直接用了一個(gè)requests庫,selenium 和xpath進(jìn)行一整頁數(shù)據(jù)的爬取
我們爬取的網(wǎng)站:https://www.anjuke.com/sy-city.html
獲取的內(nèi)容:包括地區(qū)名空繁,地區(qū)鏈接:
安居客詳情
1 一開始直接用requests庫進(jìn)行網(wǎng)站的爬取殿衰,會(huì)訪問不到數(shù)據(jù)的, 會(huì)直接出現(xiàn) 訪問的頁面出現(xiàn)錯(cuò)誤的信息盛泡。(ps:這里就暫時(shí)不打印出來了闷祥。)
2 因?yàn)橐恢眻?bào)錯(cuò),腦瓜子不知道怎么的就想到了selenium 這個(gè)框架傲诵,可能是爬安居客之前用selenium 爬取了天貓的商品內(nèi)容吧凯砍。
3 selenium 的使用,我的博客上有說過:
http:/blog.csdn.net/xudailong_blog/
4 現(xiàn)在貼上代碼片段:
# -*- coding: utf-8 -*-
# @Time : 2017/9/19 21:36
# @Author : 蛇崽
# @Email : 17193337679@163.com
# @File : anjuke.py 安居客房產(chǎn)網(wǎng)
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 # 用來計(jì)數(shù),計(jì)算爬取的書一共有多少本
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)
當(dāng)然,文本存儲(chǔ)還有一些瑕疵殖熟,因?yàn)橛玫氖钦齽t表達(dá)式局待,并沒有進(jìn)行很嚴(yán)格的匹配
貼上爬取圖片:
安居客爬取圖片
正確的數(shù)據(jù) 650條左右,因?yàn)閱柫艘幌陆o需求的小姐姐菱属,說是可以钳榨,所以就這樣子處理了。
代碼就是上面那些纽门,以后有同樣入門的一塊學(xué)習(xí)的小伙伴或者需要幫忙爬蟲的薛耻,可以私信我,我可以試著去爬一下赏陵,因?yàn)樽约阂彩亲詫W(xué)3個(gè)月左右饼齿。代碼有放到GitHub上了