python爬淘宝评论源代码_python3爬取淘宝信息代码分析
# encoding:utf-8
import re # 使用正則 匹配想要的數(shù)據(jù)
import requests # 使用requests得到網(wǎng)頁源碼
這個函數(shù)是用來得到源碼
# 得到主函數(shù)傳入的鏈接
def getHtmlText(url):
try: # 異常處理
# 得到你傳入的URL鏈接 設(shè)置超時時間3秒
r = requests.get(url, timeout=3)
# 判斷它的http狀態(tài)碼
r.raise_for_status()
# 設(shè)置它的編碼 encoding是設(shè)置它的頭部編碼 apparent_encoding是從返回網(wǎng)頁中分析它的編碼格式
r.encoding = r.apparent_encoding
# 返回源代碼
return r.text
except: # 發(fā)生異常返回空
return ''
這個函數(shù)使用來解析你的源代碼 獲取你想要的數(shù)據(jù)
# 解析你的網(wǎng)頁信息
def parsePage(ilt, html):
# 異常處理
try:
# 找到書包的價格
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
# 找到書包的名稱
tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)
# 找到書包的地址
add = re.findall(r'\"item_loc\"\:\".*?\"', html)
# 找到書包的圖片鏈接
img = re.findall(r'\"pic_url\"\:\".*?\"', html)
# 得到這個內(nèi)容放入主函數(shù)中的列表
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
address = eval(add[i].split(':')[1])
imgs = eval(img[i].split(':')[1])
ilt.append([price, title, address, imgs])
except: # 放生異常輸出空字符串
print('')
# 得到主函數(shù)傳入的列表
def printGoodsList(ilt):
# 每個列之間用tplt的放是隔開
tplt = '{:4}\t{:8}\t{:16}\t{:32}'
# 這個是整個的標(biāo)題
print(tplt.format('序號', '價格', '商品名稱','地址', '圖片地址'))
count = 0 # 統(tǒng)計有多少的序號
for g in ilt:
count = count + 1 # 循環(huán)一遍加一
print(tplt.format(count, g[0], g[1], g[2]), g[3]) # 輸出你得到的數(shù)據(jù)
# 定義主函數(shù) main
def main():
goods = '書包' # 你要搜索的東西
depth = 2 # 你想要得到幾頁的東西
start_url = 'https://s.taobao.com/search?q=' + goods # 你搜索的網(wǎng)址加上你的搜索東西
infoList = [] # 自定義的空列表用來存放你的到的數(shù)據(jù)
for i in range(depth): # 循環(huán)你的頁數(shù)
try: # 異常處理
url = start_url + '&s' + str(44 * i) # 得到你的網(wǎng)址
html = getHtmlText(url) # 得到url傳入到你要得到url的函數(shù)中
parsePage(infoList, html) # 得到你的html源碼 放入解析的網(wǎng)頁中
except: # 發(fā)生異常跳過
continue
# 把列表中的數(shù)據(jù)放入解析的函數(shù)中
printGoodsList(infoList)
# 代碼調(diào)試片段
if __name__ == '__main__':
main() # 調(diào)用主函數(shù)
以上就是經(jīng)過小編測試過的用python3爬取淘寶信息的代碼,大家測試后如果還有任何不明白的地方可以在下方的留言區(qū)討論。
總結(jié)
以上是生活随笔為你收集整理的python爬淘宝评论源代码_python3爬取淘宝信息代码分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: haproxy概念和负载均衡
- 下一篇: 博弈论Python仿真(二)