1. 程式人生 > >爬蟲問題匯總 + 解決

爬蟲問題匯總 + 解決

爬蟲 pre 如何解決 find 表達 亂碼 如何 python findall

1.如何使用正則表達式匹配中文

dir_name_list = re.findall(r‘<span id="thread_subject">([A-Za-z0-9\x80-\xfff\.()\s\[\]\-\+]+)</span>‘,str)

 使用其中的\x80-\xfff,網上有些教程寫為\x80-\xff,實際使用中發現只能匹配雙字節的中文,個人更改為三字節。

2.匹配到的中文,如何正確打印、不亂碼

dir_name.decode(‘gb2312‘).encode(‘utf-8‘)

3.urllib.urlretrieve函數無超時參數,如何解決

# urllib.urlretrieve(each_pic,pic_name)
request = requests.get(each_pic,timeout=10,stream=True)
with open(pic_name, ‘wb‘) as fh:
    # Walk through the request response in chunks of 1024 * 1024 bytes, so 1MiB
    for chunk in request.iter_content(10240 * 10240):
        # Write the chunk to the file
        fh.write(chunk)

網上有說在socket中設置timeout,這樣是不行的,timeout後程序停止。  

  

爬蟲問題匯總 + 解決