強調一下,我並不是一個程序員,因為最近需要去爬某個網站的信息寫的這個程序。程序中有很多不規範的地方,也沒用運用函數。只適合有簡單爬蟲需要的人參考。數據量大的時候採集速度很慢。
也希望有大佬能優化一下。
程序是基於python3的
import urllib.request
import re
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii') #這裡是創建一個excel把爬取到的數據儲存到表格中
worksheet = workbook.add_sheet('My Worksheet') #在excel中創建一個表單
style = xlwt.XFStyle() # 初始化樣式
font = xlwt.Font() # 為樣式創建字體
font.name = 'Times New Roman'
font.bold = True # 黑體
font.underline = True # 下劃線
font.italic = True # 斜體字
style.font = font # 設定樣式
# with open('cal.txt','r') as f: # 讀取txt生成列表 這裡是在我爬去了全部數據後篩選的一些對我有用的頁面信息編碼
# line = f.read().strip()
# linestr = line.split("\n")
count = 135
while (count < 9300):
try:
u = "http://****************/" #url前綴
url=(u +str(count))
header = {"User-Agent": "Mozilla5.0 (Windows NT 6.1; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0"} #這個頭是我複製粘貼的 就帶著就好了不用改
request = urllib.request.Request(url, headers=header) #請求網頁
response = urllib.request.urlopen(request,timeout=60) #timeout設置超時的時間,防止出現訪問超時問題
# 取出json文件裡的內容,返回的格式是字符串
html = response.read()
# 把json形式的字符串轉換成python形式的Unicode字符串,unicodestr為數組
html = html.decode("UTF-8",)
reg1 = re.compile(r'(.*?)')
reg = re.compile(r'投票(.*?)')
url1 = re.findall(reg1, html)
url = re.findall(reg, html)
print('序號:', count, '作品編號', str(count), '作品名:', url1, '得票數:', url)
worksheet.write(count, 0, count) # 第一行第一列
worksheet.write(count, 1, url1) # 第二行第二列
worksheet.write(count, 2, url) # 第二行第二列
workbook.save('**********.xls') # 保存文件
count += 1
except Exception as e:
print('a', str(e))