马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 chunguang 于 2018-8-8 15:54 编辑
我的代码如下:import requests
import json
import re
import csv
from io import StringIO
from urllib.request import urlopen
from multiprocessing import Pool
from requests.exceptions import RequestException
def get_one_page(url):
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
try:
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):
f = open(r'C:\Users\lenovo\Desktop\爬虫\烟草\烟草新闻.csv', 'a')
writer = csv.DictWriter(f, ['title', 'time'])
pattern=re.compile('<li>.*?blank">(.*?)</a></em><span>(.*?)</span></li>',re.S)
items=re.findall(pattern,html)
for item in items:
data={
'title':item[0].replace(' ',''),
'time':item[1]
}
yield data
writer.writerow(data)
def main(page):
if page != 1:#第一页不用page的形式
url='http://www.echinatobacco.com/html/site27/ynzlyns/index'+'_'+str(page)+'.html'
else:
url='http://www.echinatobacco.com//html/site27/ynzlyns/index.html'
html=get_one_page(url)
for item in parse_one_page(html):
print(item)
if __name__=='__main__':
pool=Pool()
pool.map(main,[i+1 for i in range(53)])
错误提示是 UnicodeEncodeError: 'gbk' codec can't encode character '\u200b' in position 0: illegal multibyte sequence
但是如果加了‘utf-8’,csv中的title就会乱码 |