爬取二手車并將數據保存在數據庫中
- 查看網頁結構分析爬取步驟
- 解密加密信息
- 將密文解密代碼:
- 進行爬取:
- 爬取函數
- 寫入解密文件函數和獲取城市函數
- 解密文件,返回正確字符串函數
- 保存到數據庫
- 運行結果
查看網頁結構分析爬取步驟
可以看出網頁使用了一定的加密
找到城市所在的位置,為之后的城市循環提供方便
解密加密信息
在加密信息的class元素可以看到加密的文件名稱
在source下面可以看到此文件 是一個woff文件
這個woff文件每天都會變化 我們可以在主頁中的head下的style下面找到這個woff文件的url鏈接,此后我們爬取頁面時每次都爬一下這個woff文件并且保存下來就可以避免數據錯誤
將密文解密代碼:
# 讀取加密文件進行密令轉換tf = TTFont("./trans.woff")# 可以打印看一下tf.getGlyphOrder()是什么東西num_list = tf.getGlyphOrder()[1:]num_dict = {"zero": 0, "one": 1, "two": 2,"three": 3, "four": 4, "five": 5,"six": 6, "seven": 7, "eight": 8,"nine": 9}albnum_list = [num_dict[i] for i in num_list]# 密令轉換列表new_string = ''for i in old_str:if i.isdigit():char = albnum_list.index(int(i))new_string += str(char)else:new_string += ireturn new_string
進行爬取:
爬取函數
def spider_data(url,driver,conn,cur):# 訪問汽車信息頁面driver.get(url)li_list = driver.find_elements(By.XPATH,'//ul[@class = "row-fluid list-row js-car-list"]/li')print(li_list)print("開始獲取每一個汽車的信息!")for li in li_list:# 如果這個頁面不為空則進行trytry:# 找到汽車信息所在的位置car_info = str_tran(li.find_element(By.XPATH,"a/h3").text)car_year_mile = li.find_element(By.XPATH, "a/div[@class='mileage']/span").textcar_year = datetime.strptime(str_tran(car_year_mile).split("/")[0],"%Y年%m月").date()car_mile = re.match('(.*?)萬',str_tran(car_year_mile).split("/")[1]).group(1)car_price_total = li.find_element(By.XPATH, "a/div[@class='tags-box']/div").textcar_price_total = re.match('(.+?)萬',car_price_total).group(1)try: # 如果有首付價格則進行trycar_price_pyment = li.find_element(By.XPATH, "a//div[@class='down-payment']/div").textexcept Exception as e: # 沒有首付價格 則首付價格等于車價car_price_pyment = car_price_totalprint(car_info,car_year,car_mile,car_price_total,car_price_pyment)# 保存到數據庫中store_data(car_info,car_year,car_mile,car_price_total,car_price_pyment,conn,cur)# 頁面為空則報告錯誤 接著下一個汽車信息的爬取except Exception as e:print('********************error****************')print('*********************廣告*****************')
寫入解密文件函數和獲取城市函數
# 獲取城市拼音 和 解密的信息列表
def get_city_name(driver):password_code = []city_code = []# 先訪問一次頁面driver.get('https://www.renrenche.com/hf/ershouche/p1')# 找到城市的標簽所在位置div_list = driver.find_elements(By.XPATH,'//div[@class="area-city-letter"]/div')# 將城市的拼音全部保存到一個列表中for div in div_list:a_list = div.find_elements(By.XPATH,'a')for a in a_list:city_code.append(a.get_attribute('rrc-event-name'))# 找到密文所在htm中的位置在style中 獲取style標簽下的元素內容的方法如下url_str = driver.find_element(By.XPATH,'//style[1]').get_attribute('textContent')# 匹配獲取woff加密文件的urlwoff_url = re.match('[\s\S]+?url\(\'(.*?.woff)\'', url_str).group(1)# 使用requests請求 將文件用二進制的方式保存下來response = requests.get(woff_url,headers={'user-agent': fake_useragent.UserAgent().random})re_cont = response.contentwith open('./trans.woff', 'wb') as fp:fp.write(re_cont)# 返回城市的拼音return city_code
解密文件,返回正確字符串函數
# 讀取woff文件 然后進行將錯誤的字符串轉化成為正確的字符串
def str_tran(old_str):# 讀取加密文件進行密令轉換tf = TTFont("./trans.woff")num_list = tf.getGlyphOrder()[1:]num_dict = {"zero": 0, "one": 1, "two": 2,"three": 3, "four": 4, "five": 5,"six": 6, "seven": 7, "eight": 8,"nine": 9}albnum_list = [num_dict[i] for i in num_list]# 密令轉換列表new_string = ''for i in old_str:if i.isdigit():char = albnum_list.index(int(i))new_string += str(char)else:new_string += ireturn new_string
保存到數據庫
def store_data(car_info,car_year,car_mile,car_price_total,car_price_pyment,conn,cur):number = 0insert_sql = f"insert into car_info() values({number},'{car_info}','{car_year}','{car_mile}','{car_price_total}','{car_price_pyment}')"try:cur.execute(insert_sql)except Exception as e:conn.rollback()conn.commit()print("插入數據庫完成!")
運行結果