最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python爬取城市租房信息實(shí)戰(zhàn)分享

 更新時(shí)間:2022年04月11日 19:52:12   作者:程序員班長  
這篇文章主要介紹了Python爬取城市房租房信息實(shí)戰(zhàn)分享,先單線程爬蟲,測(cè)試可以成功爬取之后再優(yōu)化為多線程,最后存入數(shù)據(jù)庫,需要的小伙伴可以參考一下的相關(guān)資料

思路:先單線程爬蟲,測(cè)試可以成功爬取之后再優(yōu)化為多線程,最后存入數(shù)據(jù)庫

以爬取鄭州市租房信息為例

注意:本實(shí)戰(zhàn)項(xiàng)目僅以學(xué)習(xí)為目的,為避免給網(wǎng)站造成太大壓力,請(qǐng)將代碼中的num修改成較小的數(shù)字,并將線程改小

一、單線程爬蟲

# 用session取代requests
# 解析庫使用bs4
# 并發(fā)庫使用concurrent
import requests
# from lxml import etree ? ?# 使用xpath解析
from bs4 import BeautifulSoup
from urllib import parse
import re
import time
?
headers = {
? ? 'referer': 'https://zz.zu.fang.com/',
? ? 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
? ? 'cookie': 'global_cookie=ffzvt3kztwck05jm6twso2wjw18kl67hqft; city=zz; integratecover=1; __utma=147393320.427795962.1613371106.1613371106.1613371106.1; __utmc=147393320; __utmz=147393320.1613371106.1.1.utmcsr=zz.fang.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmt_t0=1; __utmt_t1=1; __utmt_t2=1; ASP.NET_SessionId=aamzdnhzct4i5mx3ak4cyoyp; Rent_StatLog=23d82b94-13d6-4601-9019-ce0225c092f6; Captcha=61584F355169576F3355317957376E4F6F7552365351342B7574693561766E63785A70522F56557370586E3376585853346651565256574F37694B7074576B2B34536C5747715856516A4D3D; g_sourcepage=zf_fy%5Elb_pc; unique_cookie=U_ffzvt3kztwck05jm6twso2wjw18kl67hqft*6; __utmb=147393320.12.10.1613371106'
}
data={
? ? 'agentbid':''
}
?
session = requests.session()
session.headers = headers
?
# 獲取頁面
def getHtml(url):
? ? try:
? ? ? ? re = session.get(url)
? ? ? ? re.encoding = re.apparent_encoding
? ? ? ? return re.text
? ? except:
? ? ? ? print(re.status_code)
?
# 獲取頁面總數(shù)量
def getNum(text):
? ? soup = BeautifulSoup(text, 'lxml')
? ? txt = soup.select('.fanye .txt')[0].text
? ? # 取出“共**頁”中間的數(shù)字
? ? num = re.search(r'\d+', txt).group(0)
? ? return num
?
# 獲取詳細(xì)鏈接
def getLink(tex):
? ? soup=BeautifulSoup(text,'lxml')
? ? links=soup.select('.title a')
? ? for link in links:
? ? ? ? href=parse.urljoin('https://zz.zu.fang.com/',link['href'])
? ? ? ? hrefs.append(href)
?
# 解析頁面
def parsePage(url):
? ? res=session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding=res.apparent_encoding
? ? ? ? soup=BeautifulSoup(res.text,'lxml')
? ? ? ? try:
? ? ? ? ? ? title=soup.select('div .title')[0].text.strip().replace(' ','')
? ? ? ? ? ? price=soup.select('div .trl-item')[0].text.strip()
? ? ? ? ? ? block=soup.select('.rcont #agantzfxq_C02_08')[0].text.strip()
? ? ? ? ? ? building=soup.select('.rcont #agantzfxq_C02_07')[0].text.strip()
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[2].text.strip()
? ? ? ? ? ? except:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[1].text.strip()
? ? ? ? ? ? detail1=soup.select('.clearfix')[4].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail2=soup.select('.clearfix')[5].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail=detail1+detail2
? ? ? ? ? ? name=soup.select('.zf_jjname')[0].text.strip()
? ? ? ? ? ? buserid=re.search('buserid: \'(\d+)\'',res.text).group(1)
? ? ? ? ? ? phone=getPhone(buserid)
? ? ? ? ? ? print(title,price,block,building,address,detail,name,phone)
? ? ? ? ? ? house = (title, price, block, building, address, detail, name, phone)
? ? ? ? ? ? info.append(house)
? ? ? ? except:
? ? ? ? ? ? pass
? ? else:
? ? ? ? print(re.status_code,re.text)
?
# 獲取代理人號(hào)碼
def getPhone(buserid):
? ? url='https://zz.zu.fang.com/RentDetails/Ajax/GetAgentVirtualMobile.aspx'
? ? data['agentbid']=buserid
? ? res=session.post(url,data=data)
? ? if res.status_code==200:
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
? ? ? ? return
?
if __name__ == '__main__':
? ? start_time=time.time()
? ? hrefs=[]
? ? info=[]
? ? init_url = 'https://zz.zu.fang.com/house/'
? ? num=getNum(getHtml(init_url))
? ? for i in range(0,num):
? ? ? ? url = f'https://zz.zu.fang.com/house/i3{i+1}/'
? ? ? ? text=getHtml(url)
? ? ? ? getLink(text)
? ? print(hrefs)
? ? for href in hrefs:
? ? ? ? parsePage(href)
?
? ? print("共獲取%d條數(shù)據(jù)"%len(info))
? ? print("共耗時(shí){}".format(time.time()-start_time))
? ? session.close()

二、優(yōu)化為多線程爬蟲

# 用session取代requests
# 解析庫使用bs4
# 并發(fā)庫使用concurrent
import requests
# from lxml import etree ? ?# 使用xpath解析
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from urllib import parse
import re
import time
?
headers = {
? ? 'referer': 'https://zz.zu.fang.com/',
? ? 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
? ? 'cookie': 'global_cookie=ffzvt3kztwck05jm6twso2wjw18kl67hqft; integratecover=1; city=zz; keyWord_recenthousezz=%5b%7b%22name%22%3a%22%e6%96%b0%e5%af%86%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014868%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e4%ba%8c%e4%b8%83%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014864%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e9%83%91%e4%b8%9c%e6%96%b0%e5%8c%ba%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a0842%2f%22%2c%22sort%22%3a1%7d%5d; __utma=147393320.427795962.1613371106.1613558547.1613575774.5; __utmc=147393320; __utmz=147393320.1613575774.5.4.utmcsr=zz.fang.com|utmccn=(referral)|utmcmd=referral|utmcct=/; ASP.NET_SessionId=vhrhxr1tdatcc1xyoxwybuwv; g_sourcepage=zf_fy%5Elb_pc; Captcha=4937566532507336644D6557347143746B5A6A6B4A7A48445A422F2F6A51746C67516F31357446573052634562725162316152533247514250736F72775566574A2B33514357304B6976343D; __utmt_t0=1; __utmt_t1=1; __utmt_t2=1; __utmb=147393320.9.10.1613575774; unique_cookie=U_0l0d1ilf1t0ci2rozai9qi24k1pkl9lcmrs*4'
}
data={
? ? 'agentbid':''
}
?
session = requests.session()
session.headers = headers
?
# 獲取頁面
def getHtml(url):
? ? res = session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding = res.apparent_encoding
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
?
# 獲取頁面總數(shù)量
def getNum(text):
? ? soup = BeautifulSoup(text, 'lxml')
? ? txt = soup.select('.fanye .txt')[0].text
? ? # 取出“共**頁”中間的數(shù)字
? ? num = re.search(r'\d+', txt).group(0)
? ? return num
?
# 獲取詳細(xì)鏈接
def getLink(url):
? ? text=getHtml(url)
? ? soup=BeautifulSoup(text,'lxml')
? ? links=soup.select('.title a')
? ? for link in links:
? ? ? ? href=parse.urljoin('https://zz.zu.fang.com/',link['href'])
? ? ? ? hrefs.append(href)
?
# 解析頁面
def parsePage(url):
? ? res=session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding=res.apparent_encoding
? ? ? ? soup=BeautifulSoup(res.text,'lxml')
? ? ? ? try:
? ? ? ? ? ? title=soup.select('div .title')[0].text.strip().replace(' ','')
? ? ? ? ? ? price=soup.select('div .trl-item')[0].text.strip()
? ? ? ? ? ? block=soup.select('.rcont #agantzfxq_C02_08')[0].text.strip()
? ? ? ? ? ? building=soup.select('.rcont #agantzfxq_C02_07')[0].text.strip()
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[2].text.strip()
? ? ? ? ? ? except:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[1].text.strip()
? ? ? ? ? ? detail1=soup.select('.clearfix')[4].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail2=soup.select('.clearfix')[5].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail=detail1+detail2
? ? ? ? ? ? name=soup.select('.zf_jjname')[0].text.strip()
? ? ? ? ? ? buserid=re.search('buserid: \'(\d+)\'',res.text).group(1)
? ? ? ? ? ? phone=getPhone(buserid)
? ? ? ? ? ? print(title,price,block,building,address,detail,name,phone)
? ? ? ? ? ? house = (title, price, block, building, address, detail, name, phone)
? ? ? ? ? ? info.append(house)
? ? ? ? except:
? ? ? ? ? ? pass
? ? else:
? ? ? ? print(re.status_code,re.text)
?
# 獲取代理人號(hào)碼
def getPhone(buserid):
? ? url='https://zz.zu.fang.com/RentDetails/Ajax/GetAgentVirtualMobile.aspx'
? ? data['agentbid']=buserid
? ? res=session.post(url,data=data)
? ? if res.status_code==200:
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
? ? ? ? return
?
if __name__ == '__main__':
? ? start_time=time.time()
? ? hrefs=[]
? ? info=[]
? ? init_url = 'https://zz.zu.fang.com/house/'
? ? num=getNum(getHtml(init_url))
? ? with ThreadPoolExecutor(max_workers=5) as t:
? ? ? ? for i in range(0,num):
? ? ? ? ? ? url = f'https://zz.zu.fang.com/house/i3{i+1}/'
? ? ? ? ? ? t.submit(getLink,url)
? ? print("共獲取%d個(gè)鏈接"%len(hrefs))
? ? print(hrefs)
? ? with ThreadPoolExecutor(max_workers=30) as t:
? ? ? ? for href in hrefs:
? ? ? ? ? ? t.submit(parsePage,href)
? ? print("共獲取%d條數(shù)據(jù)"%len(info))
? ? print("耗時(shí){}".format(time.time()-start_time))
? ? session.close()

三、使用asyncio進(jìn)一步優(yōu)化

# 用session取代requests
# 解析庫使用bs4
# 并發(fā)庫使用concurrent
import requests
# from lxml import etree ? ?# 使用xpath解析
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from urllib import parse
import re
import time
import asyncio
?
headers = {
? ? 'referer': 'https://zz.zu.fang.com/',
? ? 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
? ? 'cookie': 'global_cookie=ffzvt3kztwck05jm6twso2wjw18kl67hqft; integratecover=1; city=zz; keyWord_recenthousezz=%5b%7b%22name%22%3a%22%e6%96%b0%e5%af%86%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014868%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e4%ba%8c%e4%b8%83%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014864%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e9%83%91%e4%b8%9c%e6%96%b0%e5%8c%ba%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a0842%2f%22%2c%22sort%22%3a1%7d%5d; __utma=147393320.427795962.1613371106.1613558547.1613575774.5; __utmc=147393320; __utmz=147393320.1613575774.5.4.utmcsr=zz.fang.com|utmccn=(referral)|utmcmd=referral|utmcct=/; ASP.NET_SessionId=vhrhxr1tdatcc1xyoxwybuwv; g_sourcepage=zf_fy%5Elb_pc; Captcha=4937566532507336644D6557347143746B5A6A6B4A7A48445A422F2F6A51746C67516F31357446573052634562725162316152533247514250736F72775566574A2B33514357304B6976343D; __utmt_t0=1; __utmt_t1=1; __utmt_t2=1; __utmb=147393320.9.10.1613575774; unique_cookie=U_0l0d1ilf1t0ci2rozai9qi24k1pkl9lcmrs*4'
}
data={
? ? 'agentbid':''
}
?
session = requests.session()
session.headers = headers
?
# 獲取頁面
def getHtml(url):
? ? res = session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding = res.apparent_encoding
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
?
# 獲取頁面總數(shù)量
def getNum(text):
? ? soup = BeautifulSoup(text, 'lxml')
? ? txt = soup.select('.fanye .txt')[0].text
? ? # 取出“共**頁”中間的數(shù)字
? ? num = re.search(r'\d+', txt).group(0)
? ? return num
?
# 獲取詳細(xì)鏈接
def getLink(url):
? ? text=getHtml(url)
? ? soup=BeautifulSoup(text,'lxml')
? ? links=soup.select('.title a')
? ? for link in links:
? ? ? ? href=parse.urljoin('https://zz.zu.fang.com/',link['href'])
? ? ? ? hrefs.append(href)
?
# 解析頁面
def parsePage(url):
? ? res=session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding=res.apparent_encoding
? ? ? ? soup=BeautifulSoup(res.text,'lxml')
? ? ? ? try:
? ? ? ? ? ? title=soup.select('div .title')[0].text.strip().replace(' ','')
? ? ? ? ? ? price=soup.select('div .trl-item')[0].text.strip()
? ? ? ? ? ? block=soup.select('.rcont #agantzfxq_C02_08')[0].text.strip()
? ? ? ? ? ? building=soup.select('.rcont #agantzfxq_C02_07')[0].text.strip()
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[2].text.strip()
? ? ? ? ? ? except:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[1].text.strip()
? ? ? ? ? ? detail1=soup.select('.clearfix')[4].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail2=soup.select('.clearfix')[5].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail=detail1+detail2
? ? ? ? ? ? name=soup.select('.zf_jjname')[0].text.strip()
? ? ? ? ? ? buserid=re.search('buserid: \'(\d+)\'',res.text).group(1)
? ? ? ? ? ? phone=getPhone(buserid)
? ? ? ? ? ? print(title,price,block,building,address,detail,name,phone)
? ? ? ? ? ? house = (title, price, block, building, address, detail, name, phone)
? ? ? ? ? ? info.append(house)
? ? ? ? except:
? ? ? ? ? ? pass
? ? else:
? ? ? ? print(re.status_code,re.text)
?
# 獲取代理人號(hào)碼
def getPhone(buserid):
? ? url='https://zz.zu.fang.com/RentDetails/Ajax/GetAgentVirtualMobile.aspx'
? ? data['agentbid']=buserid
? ? res=session.post(url,data=data)
? ? if res.status_code==200:
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
? ? ? ? return
?
# 獲取詳細(xì)鏈接的線程池
async def Pool1(num):
? ? loop=asyncio.get_event_loop()
? ? task=[]
? ? with ThreadPoolExecutor(max_workers=5) as t:
? ? ? ? for i in range(0,num):
? ? ? ? ? ? url = f'https://zz.zu.fang.com/house/i3{i+1}/'
? ? ? ? ? ? task.append(loop.run_in_executor(t,getLink,url))
?
# 解析頁面的線程池
async def Pool2(hrefs):
? ? loop=asyncio.get_event_loop()
? ? task=[]
? ? with ThreadPoolExecutor(max_workers=30) as t:
? ? ? ? for href in hrefs:
? ? ? ? ? ? task.append(loop.run_in_executor(t,parsePage,href))
?
if __name__ == '__main__':
? ? start_time=time.time()
? ? hrefs=[]
? ? info=[]
? ? task=[]
? ? init_url = 'https://zz.zu.fang.com/house/'
? ? num=getNum(getHtml(init_url))
? ? loop = asyncio.get_event_loop()
? ? loop.run_until_complete(Pool1(num))
? ? print("共獲取%d個(gè)鏈接"%len(hrefs))
? ? print(hrefs)
? ? loop.run_until_complete(Pool2(hrefs))
? ? loop.close()
? ? print("共獲取%d條數(shù)據(jù)"%len(info))
? ? print("耗時(shí){}".format(time.time()-start_time))
? ? session.close()

四、存入Mysql數(shù)據(jù)庫

(一)建表

from sqlalchemy import create_engine
from sqlalchemy import String, Integer, Column, Text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session ?# 多線程爬蟲時(shí)避免出現(xiàn)線程安全問題
from sqlalchemy.ext.declarative import declarative_base
?
BASE = declarative_base() ?# 實(shí)例化
engine = create_engine(
? ? "mysql+pymysql://root:root@127.0.0.1:3306/pytest?charset=utf8",
? ? max_overflow=300, ?# 超出連接池大小最多可以創(chuàng)建的連接
? ? pool_size=100, ?# 連接池大小
? ? echo=False, ?# 不顯示調(diào)試信息
)
?
?
class House(BASE):
? ? __tablename__ = 'house'
? ? id = Column(Integer, primary_key=True, autoincrement=True)
? ? title=Column(String(200))
? ? price=Column(String(200))
? ? block=Column(String(200))
? ? building=Column(String(200))
? ? address=Column(String(200))
? ? detail=Column(Text())
? ? name=Column(String(20))
? ? phone=Column(String(20))
?
?
BASE.metadata.create_all(engine)
Session = sessionmaker(engine)
sess = scoped_session(Session)

(二)將數(shù)據(jù)存入數(shù)據(jù)庫中 

# 用session取代requests
# 解析庫使用bs4
# 并發(fā)庫使用concurrent
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from urllib import parse
from mysqldb import sess, House
import re
import time
import asyncio
?
headers = {
? ? 'referer': 'https://zz.zu.fang.com/',
? ? 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
? ? 'cookie': 'global_cookie=ffzvt3kztwck05jm6twso2wjw18kl67hqft; integratecover=1; city=zz; __utmc=147393320; ASP.NET_SessionId=vhrhxr1tdatcc1xyoxwybuwv; __utma=147393320.427795962.1613371106.1613575774.1613580597.6; __utmz=147393320.1613580597.6.5.utmcsr=zz.fang.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmt_t0=1; __utmt_t1=1; __utmt_t2=1; Rent_StatLog=c158b2a7-4622-45a9-9e69-dcf6f42cf577; keyWord_recenthousezz=%5b%7b%22name%22%3a%22%e4%ba%8c%e4%b8%83%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014864%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e9%83%91%e4%b8%9c%e6%96%b0%e5%8c%ba%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a0842%2f%22%2c%22sort%22%3a1%7d%2c%7b%22name%22%3a%22%e7%bb%8f%e5%bc%80%22%2c%22detailName%22%3a%22%22%2c%22url%22%3a%22%2fhouse-a014871%2f%22%2c%22sort%22%3a1%7d%5d; g_sourcepage=zf_fy%5Elb_pc; Captcha=6B65716A41454739794D666864397178613772676C75447A4E746C657144775A347A6D42554F446532357649643062344F6976756E563450554E59594B7833712B413579506C4B684958343D; unique_cookie=U_0l0d1ilf1t0ci2rozai9qi24k1pkl9lcmrs*14; __utmb=147393320.21.10.1613580597'
}
data={
? ? 'agentbid':''
}
?
session = requests.session()
session.headers = headers
?
# 獲取頁面
def getHtml(url):
? ? res = session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding = res.apparent_encoding
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
?
# 獲取頁面總數(shù)量
def getNum(text):
? ? soup = BeautifulSoup(text, 'lxml')
? ? txt = soup.select('.fanye .txt')[0].text
? ? # 取出“共**頁”中間的數(shù)字
? ? num = re.search(r'\d+', txt).group(0)
? ? return num
?
# 獲取詳細(xì)鏈接
def getLink(url):
? ? text=getHtml(url)
? ? soup=BeautifulSoup(text,'lxml')
? ? links=soup.select('.title a')
? ? for link in links:
? ? ? ? href=parse.urljoin('https://zz.zu.fang.com/',link['href'])
? ? ? ? hrefs.append(href)
?
# 解析頁面
def parsePage(url):
? ? res=session.get(url)
? ? if res.status_code==200:
? ? ? ? res.encoding=res.apparent_encoding
? ? ? ? soup=BeautifulSoup(res.text,'lxml')
? ? ? ? try:
? ? ? ? ? ? title=soup.select('div .title')[0].text.strip().replace(' ','')
? ? ? ? ? ? price=soup.select('div .trl-item')[0].text.strip()
? ? ? ? ? ? block=soup.select('.rcont #agantzfxq_C02_08')[0].text.strip()
? ? ? ? ? ? building=soup.select('.rcont #agantzfxq_C02_07')[0].text.strip()
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[2].text.strip()
? ? ? ? ? ? except:
? ? ? ? ? ? ? ? address=soup.select('.trl-item2 .rcont')[1].text.strip()
? ? ? ? ? ? detail1=soup.select('.clearfix')[4].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail2=soup.select('.clearfix')[5].text.strip().replace('\n\n\n',',').replace('\n','')
? ? ? ? ? ? detail=detail1+detail2
? ? ? ? ? ? name=soup.select('.zf_jjname')[0].text.strip()
? ? ? ? ? ? buserid=re.search('buserid: \'(\d+)\'',res.text).group(1)
? ? ? ? ? ? phone=getPhone(buserid)
? ? ? ? ? ? print(title,price,block,building,address,detail,name,phone)
? ? ? ? ? ? house = (title, price, block, building, address, detail, name, phone)
? ? ? ? ? ? info.append(house)
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? house_data=House(
? ? ? ? ? ? ? ? ? ? title=title,
? ? ? ? ? ? ? ? ? ? price=price,
? ? ? ? ? ? ? ? ? ? block=block,
? ? ? ? ? ? ? ? ? ? building=building,
? ? ? ? ? ? ? ? ? ? address=address,
? ? ? ? ? ? ? ? ? ? detail=detail,
? ? ? ? ? ? ? ? ? ? name=name,
? ? ? ? ? ? ? ? ? ? phone=phone
? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? sess.add(house_data)
? ? ? ? ? ? ? ? sess.commit()
? ? ? ? ? ? except Exception as e:
? ? ? ? ? ? ? ? print(e) ? ?# 打印錯(cuò)誤信息
? ? ? ? ? ? ? ? sess.rollback() ?# 回滾
? ? ? ? except:
? ? ? ? ? ? pass
? ? else:
? ? ? ? print(re.status_code,re.text)
?
# 獲取代理人號(hào)碼
def getPhone(buserid):
? ? url='https://zz.zu.fang.com/RentDetails/Ajax/GetAgentVirtualMobile.aspx'
? ? data['agentbid']=buserid
? ? res=session.post(url,data=data)
? ? if res.status_code==200:
? ? ? ? return res.text
? ? else:
? ? ? ? print(res.status_code)
? ? ? ? return
?
# 獲取詳細(xì)鏈接的線程池
async def Pool1(num):
? ? loop=asyncio.get_event_loop()
? ? task=[]
? ? with ThreadPoolExecutor(max_workers=5) as t:
? ? ? ? for i in range(0,num):
? ? ? ? ? ? url = f'https://zz.zu.fang.com/house/i3{i+1}/'
? ? ? ? ? ? task.append(loop.run_in_executor(t,getLink,url))
?
# 解析頁面的線程池
async def Pool2(hrefs):
? ? loop=asyncio.get_event_loop()
? ? task=[]
? ? with ThreadPoolExecutor(max_workers=30) as t:
? ? ? ? for href in hrefs:
? ? ? ? ? ? task.append(loop.run_in_executor(t,parsePage,href))
?
if __name__ == '__main__':
? ? start_time=time.time()
? ? hrefs=[]
? ? info=[]
? ? task=[]
? ? init_url = 'https://zz.zu.fang.com/house/'
? ? num=getNum(getHtml(init_url))
? ? loop = asyncio.get_event_loop()
? ? loop.run_until_complete(Pool1(num))
? ? print("共獲取%d個(gè)鏈接"%len(hrefs))
? ? print(hrefs)
? ? loop.run_until_complete(Pool2(hrefs))
? ? loop.close()
? ? print("共獲取%d條數(shù)據(jù)"%len(info))
? ? print("耗時(shí){}".format(time.time()-start_time))
? ? session.close()

五、最終效果圖 (已打碼)

到此這篇關(guān)于Python爬取城市租房信息實(shí)戰(zhàn)分享的文章就介紹到這了,更多相關(guān)Python爬取租房信息內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Anaconda徹底刪除虛擬環(huán)境的正確方法

    Anaconda徹底刪除虛擬環(huán)境的正確方法

    這篇文章主要給大家介紹了關(guān)于Anaconda徹底刪除虛擬環(huán)境的正確方法,要在Anaconda中刪除一個(gè)虛擬環(huán)境,可以按照本文以下步驟進(jìn)行操作,需要的朋友可以參考下
    2023-10-10
  • sklearn和keras的數(shù)據(jù)切分與交叉驗(yàn)證的實(shí)例詳解

    sklearn和keras的數(shù)據(jù)切分與交叉驗(yàn)證的實(shí)例詳解

    這篇文章主要介紹了sklearn和keras的數(shù)據(jù)切分與交叉驗(yàn)證的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • pandas DataFrame的修改方法(值、列、索引)

    pandas DataFrame的修改方法(值、列、索引)

    這篇文章主要介紹了pandas DataFrame的修改方法(值、列、索引),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • 在Python中操作字典之clear()方法的使用

    在Python中操作字典之clear()方法的使用

    這篇文章主要介紹了在Python中操作字典之clear()方法的使用,是Python入門的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-05-05
  • Go/Python/Erlang編程語言對(duì)比分析及示例代碼

    Go/Python/Erlang編程語言對(duì)比分析及示例代碼

    這篇文章主要介紹了Go/Python/Erlang編程語言對(duì)比分析及示例代碼,本文重點(diǎn)是給大家介紹go語言,從語言對(duì)比分析的角度切入介紹,需要的朋友可以參考下
    2018-04-04
  • python裝飾器"@"使用實(shí)例深入探究

    python裝飾器"@"使用實(shí)例深入探究

    這篇文章主要為大家介紹了python裝飾器"@"使用實(shí)例深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Python 函數(shù)返回值的示例代碼

    Python 函數(shù)返回值的示例代碼

    這篇文章主要介紹了Python 函數(shù)返回值的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • python中的socket實(shí)現(xiàn)ftp客戶端和服務(wù)器收發(fā)文件及md5加密文件

    python中的socket實(shí)現(xiàn)ftp客戶端和服務(wù)器收發(fā)文件及md5加密文件

    這篇文章主要介紹了python中的socket實(shí)現(xiàn)ftp客戶端和服務(wù)器收發(fā)文件及md5加密文件的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-04-04
  • 解析Python中的變量、引用、拷貝和作用域的問題

    解析Python中的變量、引用、拷貝和作用域的問題

    這篇文章主要介紹了Python中的變量、引用、拷貝和作用域的相關(guān)問題,是Python學(xué)習(xí)過程當(dāng)中必會(huì)的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-04-04
  • 用Python畫圣誕樹代碼示例

    用Python畫圣誕樹代碼示例

    大家好,本篇文章主要講的是用Python畫圣誕樹代碼示例,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12

最新評(píng)論

科尔| 甘孜| 泗洪县| 云龙县| 十堰市| 涟源市| 固镇县| 白银市| 元谋县| 伊金霍洛旗| 鄯善县| 江都市| 永善县| 武安市| 温州市| 岳阳市| 新和县| 抚松县| 兴国县| 双柏县| 达日县| 日照市| 嘉义市| 鄂尔多斯市| 徐闻县| 和顺县| 明溪县| 安西县| 淳化县| 定西市| 周至县| 陇南市| 丁青县| 会理县| 三穗县| 赫章县| 涟源市| 景德镇市| 公安县| 淮北市| 任丘市|