- 帖子
- 109
- 主題
- 1
- 精華
- 0
- 積分
- 116
- 點名
- 0
- 作業系統
- win7
- 軟體版本
- 2007
- 閱讀權限
- 20
- 註冊時間
- 2016-8-4
- 最後登錄
- 2018-10-22
 
|
74#
發表於 2016-9-11 17:59
| 只看該作者
回復 73# c_c_lai
跟get_detail放的位子也有關係(call function的時候python就會去找,如果還沒定義就會有問題)。
改了一個bug(之前會址沒處理到),加上輸出的部份。
目前的code我整理了一下,您用這個再測試看看。- import requests
- from bs4 import BeautifulSoup
- import csv
- def get_detail(url, s):
- print(url)
- res = s.get(url)
- res.encoding = 'utf-8'
- soup = BeautifulSoup(res.text, 'lxml')
- detail = soup.find_all('td', 'church_detail')
- for ddd in detail[0].stripped_strings:
- if '回報資料錯誤 >' in ddd:
- continue
- else:
- tmpList.append(ddd)
- for i, s in enumerate(tmpList):
- if s == "":
- continue
- elif any(x in s for x in ['電郵', '網址', '宗派', '母會']):
- myDict[s.replace(':', '')] = tmpList[i+1]
- elif '會址' in s:
- myDict[s.split(':')[0]] = (s.split(':')[1] + tmpList[i+1])
- else:
- try:
- myDict[s.split(':')[0]] = s.split(':')[1]
- except:
- pass
- myList.append(myDict)
- myDict = {}
- myList = []
- tmpList = []
- s = requests.session()
- for i in range(1, 2):
- url = 'http://church.oursweb.net/slocation.php?w=1&c=TW&a=&t=&p=' + str(i)
- res = s.get(url)
- res.encoding = 'utf-8'
- soup = BeautifulSoup(res.text, 'lxml')
- for d in soup.select('a[href^="church.php?pkey"]'):
- myUrl = 'http://church.oursweb.net/' + d.get('href')
- get_detail(myUrl,s)
- myDict = {}
- i += 1
- with open('gospel2.csv', 'a', new='', encoding='utf-8') as f:
- fieldnames = ['建檔 ID', '中文名稱', '英文名稱', '分類', '宗派', '母會', '網址', '國別區域', '設立時間', '負責人', '電話', '傳真', '電郵', '會址', '通訊處']
- w = csv.DictWriter(f, fieldnames)
- w.writeheader()
- w.writerows(myList)
複製代碼 |
|