爬虫问题汇总 + 解决

1.如何使用正则表达式匹配中文

dir_name_list = re.findall(r'<span id="thread_subject">([A-Za-z0-9x80-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后程序停止。  

  

原文地址:https://www.cnblogs.com/hester/p/7399630.html