python3 requests 抓取亂

遇到此問題後 設置r.encoding='gbk'或r.encoding='gb2312'後可以了

注意:gbk範圍要比gb2312要大,設置gbk要好

python用到中文轉拼音的一個包 xpinyin,但用pyinstaller生成exe時,運行提示缺包,沒解決

python讀取文件方式:

讀取:

file = open('setUrl.txt','r')

url = file.read()

file.close()

寫入:不存在創建,每次打開寫入時先清空再開始寫入

file = open('sql.txt','w') #『w』是覆蓋,『a』是追加

for i in strs:

    print(i[2])

file.write(i[2] + 'n')

file.close()

python模組安裝方法:

進入命令行直接輸入 :pip install 包名 

python打包exe 方法

進入程式目錄,用pyinstaller打包,輸入命令行:pyinstaller [-F] 打包python文件名.py 該方式在遷移後不能修改.py文件,不推薦,暫沒找到好方法,並且打包後運行會提示缺模組如「queue」要在py中引入「from multiprocessing import Queue」。

python3中全局變數使用方式,主方法中聲明,調用方法中再聲明

global 變數名

def funcA():

    global 變數名

一些網站可能簡單螢幕蔽網頁抓取,通過設置http請求標頭,可實現抓取

    UserAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'      accept = '*/*'      acceptLanguage = 'zh-Hans-CN, zh-Hans; q=0.8, en-US; q=0.5, en; q=0.3'      acceptEncoding = 'gzip, deflate, sdch'      Cookie = 'AD_RS_COOKIE=20083361; _trs_ua_s_1=em41_6_j0ywubts; _gscu_1771678062=91030129ufqfm619; _gscs_1771678062=9103012938hyzj19|pv:1; _gscbrs_1771678062=1; _trs_uv=23au_6_j0ywubts'      Host = 'www.stats.gov.cn'      CacheControl = 'no-cache'      Connection = 'Keep-Alive'      headers = { 'User-Agent' : UserAgent,'accept':accept,'accept-Encoding':acceptEncoding,'Accept-Language':acceptLanguage,'Cookie':Cookie,'Host':Host,'Cache-Control' : CacheControl,'Connection':Connection}      s = requests.Session()      s.headers.update(headers)      req = s.get(url)      req.encoding='gbk'

網頁抓取 解析html

BeautifulSoup很好用,類似jquery選擇器,可替代正則表達式