import requests
import json
import re
import time
from requests.exceptions import RequestException
url ='http://www.24timemap.com/'
def get_one_page(url):
try:
headers={
'User-Agent':'Mozilla/5.0(Macintosh;Intel Mac OS X 10_13_3)AppleWebKit/537.36(KHTML,like Gecko) Chrome/65.0.3325.162 Safari/537.36'
}
response = requests.get(url,headers=headers)
if response.status_code ==200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
pattern = re.compile('<li.*?bg.*?title.*?>(.*?)</a>(.*?)</li>',re.S)
items = re.findall(pattern,html)
for item in items:
yield {
'locantion': item[0],
'time': item[1]
}
def write_to_file(content):
with open('slw.txt', 'a', encoding='utf-8')as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
uj5u.com熱心網友回復:
縮進有問題呀。
def write_to_file(content):
with open('slw.txt', 'a', encoding='utf-8')as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
def write_to_file(content):
with open('slw.txt', 'a', encoding='utf-8')as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
uj5u.com熱心網友回復:
你好,我把縮進按照你給的格式推進了,可是還是沒法運行uj5u.com熱心網友回復:
代碼就定義了3個函式。 你想做啥?uj5u.com熱心網友回復:
> 正則運算式是正確的,但是程式無法運行的確,你的 代碼 中 正則(或許)是正確的
而你說的 無法運行,其實:已經運行了
-》已經按照你給的Python的代碼 運行了
-》運行結果就是:啥都沒干
-》為何啥都沒干,是因為你沒寫代碼讓其干活
-》具體說就是:你只定義了3個函式(其中一個函式中有你說的正則),但是卻沒呼叫(其中任何一個函式)
所以變成你說的:”代碼無法運行“
如何讓其運行?
比如代碼最后加上
pageHtml = get_one_page(url)
respGenerator = parse_one_page(pageHtml)
for eachItemDict in respGenerator:
write_to_file(eachItemDict)
就可以實作:
真正呼叫函式 執行內部的代碼和邏輯 -》變成你說希望的:代碼真的運行了。
另外,關于代碼縮進 導致你代碼運行了 但你以為沒運行,詳見:
【教程】詳解Python中代碼縮進(Indent):影響代碼的內在邏輯關系和執行結果 – 在路上
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/78146.html
