鱼C论坛

 找回密码
 立即注册
查看: 6757|回复: 13

[技术交流] 鱼C论坛Python精英挑战赛(第四季04期)

[复制链接]
发表于 2017-12-11 13:14:57 | 显示全部楼层 |阅读模式
本帖最后由 jerryxjr1220 于 2017-12-18 09:45 编辑

第四届鱼C论坛精英挑战赛开始咯!为了增加趣味性,本届仍然延续“新玩法”-- “押宝玩法”,“竞猜玩法”和“擂主玩法”。

同时,根据以往鱼油的反馈,精英赛题目普遍偏难,所以参与的鱼油相对较少。为了提高大家的参与度,本届挑战赛会大幅降低难度,使大部分鱼油都能参赛。同时,会增设一、二、三名奖励,第一名奖励50鱼币,第二名30鱼币,第三名20鱼币。

新玩法规则:

1. 押宝玩法:由于押宝玩法参与人数很少,故暂停押宝。后续有改进玩法,会再公布。

2. 竞猜玩法:直接在比赛帖的下方进行投票,凡事“竞赛”获胜者,将奖励5鱼币。竞猜无门槛,人人都可以参与。竞猜以后,请在本帖留个言,方便领取奖励。

3. 擂主玩法:上一期挑战成功的鱼油成为挑战赛的擂主,擂主有优先权提议下一期的赛题,一届挑战赛共分5期,同一届中当擂主最长的鱼油有额外奖励。

本期题目: 爬知乎日报 https://daily.zhihu.com/

不知道大家是否都看过“知乎日报”,每天3次的“知乎日报”包含了大量的信息和知识,而7分钟的阅读量也非常符合现代非常快节奏的生活。
Untitled.png

那么今天的题目就是做一个爬虫,去爬下每期的“知乎日报”,然后把爬取的网页内容(若有能力把网页内容转换成pdf加分)按照日期和标题自动归类到文件夹zhihu_daily。

加分项:自动检测知乎日报是否有更新,如果有更新,自动爬取更新的内容(不重复爬取已有的内容),自动检测频率可以设置1小时1次。

提示:“知乎日报”有网页版、安卓版、IOS版、微信小程序、API等多种版本和端口可以使用,挑选你认为最合适的爬虫策略,形式方法不限。

要求: 爬虫正常运行,程序效率高,代码简洁

截止日期: 12月17日24时

本期擂主: cngoodboy、gunjang、万事屋

@小甲鱼 @冬雪雪冬 @~风介~ @SixPy

竞猜:回答正确的参赛者的人数
单选投票, 共有 15 人参与投票
您所在的用户组没有投票权限

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-11 13:56:03 | 显示全部楼层
爬虫没学过,不会。🐶️🐶️
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-12 09:26:45 | 显示全部楼层
本帖最后由 jerryxjr1220 于 2017-12-18 09:41 编辑
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import threading
  4. import os
  5. import re
  6. import pdfkit
  7. import lxml
  8. from requests.exceptions import RequestException
  9. def get_index_page():
  10.     # headers是为了解决http 304 错误
  11.     headers={
  12.         'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  13.         'Accept-Encoding':'gzip, deflate',
  14.         'Accept-Language':'zh-CN,zh;q=0.9',
  15.         'Cache-Control':'max-age=0',
  16.         'Connection':'keep-alive',
  17.         'Host':'daily.zhihu.com',
  18.         'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3269.3 Safari/537.36'
  19.     }
  20.     url="http://daily.zhihu.com"
  21.     response=requests.get(url,headers=headers)  #启用headers参数
  22.     # print(response.text)
  23.     return response.text
  24. def get_detail_content():
  25.     # global data_G
  26.     html = get_index_page()  #获取网页文本数据
  27.     # 使用BeautifulSoup 解析
  28.     soup = BeautifulSoup(html, 'lxml')
  29.     # 按照xmlselector 查找titles 和images,href 详情地址
  30.     titles = soup.select('body > div.main-content > div > div.main-content-wrap > div > div > div > div > a > span ')
  31.     images = soup.select('body > div.main-content > div > div.main-content-wrap > div > div > div > div > a > img ')
  32.     hrefs =soup.select('body > div.main-content > div > div.main-content-wrap > div > div > div > div > a ')
  33.     for title,image,href in zip(titles,images,hrefs):
  34.         title=title.get_text()
  35.         data={
  36.             'title':re.sub(r'\W',"",title),
  37.             'image':image.get('src'),
  38.             'href':href.get('href')
  39.         }
  40.         # print(data)
  41.         yield data
  42.     print("================================")
  43. def timer_work():
  44.     global num,data_G
  45.     num=num+1
  46.     data_G = get_detail_content()
  47.     save_all()
  48.     #每1000s执行一次
  49.     t = threading.Timer(1000, timer_work)
  50.     t.start()
  51. def save_all():
  52.     # 创建文件夹
  53.     if not os.path.isdir(os.getcwd() + '/zhihu_daily'):
  54.         print("NO")
  55.         os.mkdir(os.getcwd() + '/zhihu_daily')
  56.     else:
  57.         print('OK')
  58.     for tmp in data_G:
  59.         images_save(tmp['title'],tmp['image']) #保存图片
  60.         #保存详情
  61.         PDF_save(tmp['href'],tmp['title'])
  62.     print("Done")
  63. def PDF_save(href,title):

  64.     # 解决:python使用pdfkit中,如果使用pdfkit.from_url 或者pdfkit.from_string等,就会出现上述错误。而且如果你使用pip安装了 wkhtmltopdf,还是会出现这个问题:
  65.     # If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
  66.     # 方法
  67.     # path_wk = r'D:\Users\Administrator\AppData\Local\Programs\Python\Python36\Lib\site-packages\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
  68.     # config = pdfkit.configuration(wkhtmltopdf=path_wk)
  69.     # pdfkit.from_url(url,file_path,configuration=config)

  70.     path_wk = r'D:\Users\Administrator\AppData\Local\Programs\Python\Python36\Lib\site-packages\wkhtmltopdf\bin\wkhtmltopdf.exe'  # 安装位置
  71.     config = pdfkit.configuration(wkhtmltopdf=path_wk)
  72.     url='https://daily.zhihu.com'+href
  73.     # print(title+'.pdf')
  74.     file_path="{0}/{1}/{2}.{3}".format(os.getcwd(),'zhihu_daily',title , 'pdf')
  75.     try:
  76.         if not os.path.exists(file_path):
  77.             pdfkit.from_url(url,file_path,configuration=config)
  78.         else:
  79.             print("TP2:文件存在")
  80.     except:
  81.         # 此处一个Exit with code 1 due to network error: ContentNotFoundError异常
  82.         # 此异常为是因为css文件引用了外部的资源,如:字体,图片,iframe加载等。
  83.         # 选择忽略此异常
  84.         pass

  85. def images_save(title,image):
  86.     img = requests.get(image)     #获取图片的response
  87.     # title1=re.sub(r'\W',"",title) #标题去掉特殊符号,如 ?  不然会出现无法保存的错误
  88.     file_path = "{0}/{1}/{2}.{3}".format(os.getcwd(),'zhihu_daily',title , 'jpg') #格式化存放路径
  89.     if not os.path.exists(file_path):
  90.         with open(file_path, 'wb') as f:
  91.             f.write(img.content)         # 存放图片
  92.             f.close()
  93. def main():
  94.     timer_work() #每一个小时刷新一次

  95. data_G={}
  96. if __name__=='__main__':
  97.     num=0
  98.     main()
复制代码
QQ图片20171216224923.png

点评

不单单只是爬取封面和标题哦,要爬每期的内容哦  发表于 2017-12-14 09:13

评分

参与人数 1荣誉 +2 鱼币 +2 贡献 +2 收起 理由
jerryxjr1220 + 2 + 2 + 2 答题奖励

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-12 10:53:07 | 显示全部楼层

python3转了一下

本帖最后由 jerryxjr1220 于 2017-12-15 09:44 编辑

   
  1. import random, requests, time
  2. from bs4 import BeautifulSoup
  3. import re
  4. user_agents = [
  5.                 'ozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
  6.                 'Opera/9.25 (Windows NT 5.1; U; en)',
  7.                 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
  8.                 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
  9.                 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
  10.                 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
  11.                 "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
  12.                 "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",
  13.                                         ]
  14.         user_agent = random.choice(user_agents)
  15.         headers = {
  16.                 'user-agent': user_agent,
  17.                 'accept': '* / *',
  18.                 'accept - encoding': 'gzip, deflate, br',
  19.                 'accept - language': 'zh - CN, zh;q = 0.9',
  20.                         }

  21.         url = "https://daily.zhihu.com"
  22.         r = requests.get(url,headers=headers)
  23.         soup = BeautifulSoup(r.content, 'lxml')
  24.         s = soup.select('div[class="box"]')
  25.         print(time.strftime('%Y-%m-%d',time.localtime(time.time())) + ':知乎日报标题内容速览')
  26.         for i in range(len(s)):
  27.                 link = re.findall(r'<a class="link-button" href="(.*?)">',str(s[i]))
  28.                 title = re.findall(r'<span class="title">(.*?)<\/span>',str(s[i]))
  29.                 img = re.findall(r'src="(.*?)"',str(s[i]))
  30.                 title = urllib.parse.unquote(''.join(title))
  31.                 print( url+''.join(link), title ,'img= %s'%''.join(img))
  32.                 res = requests.get(url+''.join(link), headers=headers)
  33.                 soup = BeautifulSoup(res.content, 'lxml')
  34.                 so = soup.select('div[class="question"]')
  35.                 contents = re.findall(r'>(.*?)<',str(so))
  36.                 print( ''.join(contents))
复制代码



点评

不仅仅是要标题哦,里面的内容也需要爬的。  发表于 2017-12-15 09:43

评分

参与人数 1荣誉 +2 鱼币 +2 贡献 +2 收起 理由
jerryxjr1220 + 2 + 2 + 2 答题奖励,最好能换python3了,这是大趋势.

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-12 20:10:45 | 显示全部楼层

111

本帖最后由 qwc3000 于 2017-12-16 23:32 编辑

点评

运行报错: TypeError: get_detail_content() missing 1 required positional argument: 'num1'  发表于 2017-12-12 22:18
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-15 06:44:30 | 显示全部楼层
我投票中了吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-15 08:46:33 | 显示全部楼层
看看是什么情况!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-15 23:47:40 | 显示全部楼层
这个有意思呀!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-18 09:40:16 | 显示全部楼层
很棒棒的题目。可惜不会爬虫
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-12-18 10:40:49 | 显示全部楼层
SylarPu 发表于 2017-12-18 09:40
很棒棒的题目。可惜不会爬虫

可以参考获胜者的程序,写得很棒!输出的pdf也很优雅!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-12-18 14:29:02 | 显示全部楼层

问个问题哈,请问 使用requests.get之后,如果直接print r.text 报错,gbk错误,是我的电脑的问题么
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-19 14:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表