我用python學英語(一)

2021-10-20 01:13:21 字數 4556 閱讀 7773

最近一年有了考雅思的想法,正好最近工作嚴重不飽和(摸魚摸得飛起),同時又在向同事學python爬蟲,好了,這兩件事結合下唄,既能練習到爬蟲知識,還能順便爬爬英語學習資料。

這個**無需登入,所以比較簡單,用到了 xpath 和 beautifulsoup 來提取 html 內容 ,還用到了 pytesseract 來提取中的文字,只是效果非常不好 orz。**如下

from datetime import datetime, timedelta

from urllib.parse import urljoin

from bs4 import beautifulsoup

import time

import json

import platform

import requests

from lxml import etree

import pytesseract

from pil import image

import urllib.request

import io

import logging

import os.path

class spokenandwritten(object):

head =

url = ""

# 建立乙個logger

logger = logging.getlogger()

def __init__(self):

self.sess = requests.session()

self.init_log()

def init_log(self):

# log等級總開關

self.logger.setlevel(logging.info)

# 第二步,建立乙個handler,用於寫入日誌檔案

rq = time.strftime('%y%m%d%h%m', time.localtime(time.time()))

log_path = '.\\logs\\'

log_name = log_path + rq + '.log'

logfile = log_name

fh = logging.filehandler(logfile, mode='w', encoding="utf-8")

# 輸出到file的log等級的開關

fh.setlevel(logging.info)

# 第三步,定義handler的輸出格式

formatter = logging.formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")

fh.setformatter(formatter)

# 第四步,將logger新增到handler裡面

self.logger.addhandler(fh)

# # 日誌列印到螢幕上

ch = logging.streamhandler()

ch.setlevel(logging.info)

self.logger.addhandler(ch)

def list_page(self,day_limit):

is_continue= true

page = 1

while(is_continue) :

self.logger.info(f"...... 第 頁 ......")

if page == 1 :

res = requests.get(self.url, params=none, headers=self.head, timeout=(10, 20))

else :

res = requests.get(self.url+'/page/'+str(page), headers=self.head, timeout=(10, 20))

html = etree.html(res.text)

if page == 1 :

result_page = html.xpath("//*[@class='page-numbers']/text()")

if result_page == none :

return

else :

pagenum = int(result_page[-1])

self.logger.info(f"...... 獲取分頁 頁數 : ")

results = html.xpath('//h3[contains(@class,"entry-title mh-loop-title")]//a/@href')

update_time = html.xpath("//*[@class='mh-loop-header']//*[@class='mh-meta-date updated']/text()")

latest = datetime.strptime(update_time[-1], "%y年%m月%d日")

is_continue = latest >= datetime.strptime(day_limit, "%y-%m-%d")

for result in results:

self.detail_page(result)

if(is_continue) :

page = page + 1

is_continue = page <= pagenum

def detail_page(self, detail_url):

self.logger.info("...... 詳情頁面 ......")

res = requests.get(detail_url, headers=self.head, timeout=(10, 20))

soup = beautifulsoup(res.text, 'lxml')

strongs = soup.article

title = soup.find(attrs=).text

title = title.replace(",","-").replace("、","-").replace("|","-").replace(' ', '')

self.logger.info(f"...... 文章標題 ......")

img_text_chi = ''

try :

text_img = soup.find('strong',text='影視用例').parent.find_next_siblings()[0].next.get('src')

url_img = urllib.request.urlopen(text_img)

temp_img = io.bytesio(url_img.read())

image = image.open(temp_img)

img_text_chi_contain = pytesseract.image_to_string(image, lang='chi_sim')

img_text_eng = pytesseract.image_to_string(image)

for chi in img_text_chi_contain :

if u'\u4e00' <= chi <= u'\u9fff':

img_text_chi = img_text_chi + chi

img_text_eng = img_text_eng.rsplit('\n\x0c')[0].split('\n')[-1]

except exception :

if len(img_text_chi) == 0 :

self.logger.info("...... 未解析成功文字 ......")

article = strongs.text

else :

article_split = strongs.text.split('\n影視用例\n\n')

article = article_split[0] + '\n影視用例\n\n' + img_text_chi + '\n\n' + img_text_eng + '\n\n\x0c' + article_split[1]

try :

self.logger.info("...... 寫入檔案 ......")

fo = open("doc/"+title+".txt","w",encoding='utf-8')

fo.write( article + '\n')

except exception :

self.logger.error("...... 檔案寫入失敗 ......")

finally :

fo.close()

if __name__ == '__main__':

spokenandwritten().list_page(time.strftime("%y-%m-%d"))

# spokenandwritten().list_page('2019-01-01')

「享受」英語的快樂 我是如何學英語的

一 揚長避短重新認識英語課本目前市場上的課本都有弊端,新概念 走遍美國 瘋狂英語 等等,不怪你學不下去,不是你的問題,課本本身就有漏洞的,但我怎麼學的呢,我來簡要介紹下我的方式,大家互相切磋!先說課本 新概念 本身從第二套,和第三套之間就跨度很大,你說要提高閱讀和口語能力,新概念本身就是書面語言的標...

我的Python自學之路一 Python學習路線

作為以為小白,在學習python的時候,必然會走一定的彎路,有人在彎路上走丟了,有人走出了彎路。我就是屬於還未走出彎路的同學,所以我想談談我的python學習之路。我進入這個坑是因為這個最近幾年比較火,想必大家都知道吧,我開始學習python時,先學習的是linux基本命令,作為小白,在裝linux...

我是怎麼從零開始學英語的

這是我在中醫藥論壇裡寫的乙個文章,我是乙個半老頭了,就是這麼大的年紀,學英語有一年了,當然,我不是英語高手,我學英語的方法也許對你很有用。我把文章轉過來,我是怎麼從零開始學英語的 哈哈哈。在很多人眼裡 英語難,和我以前的認為一樣。其實英語是最好學的乙個語言,很有規則。遠比我們的母語中文好學。多數不要...