鱼C论坛

 找回密码
 立即注册
查看: 1355|回复: 11

[已解决]仿照爬豆瓣top250,爬先知社区标题,作者时间

[复制链接]
发表于 2020-8-4 18:20:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import requests
import bs4
import re

def open_url(url):

    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

    res = requests.get(url, headers=headers)
    return res

def find_title(res):
    soup = bs4.BeautifulSoup(res.text,'html.parser')

    #文章标题
    title = []
    targets = soup.find_all('p',class_='topic-summary')
    for each in targets:
        title.append(each.a.text)

    #资料(作者,类型,时间)
    messages = []
    targets = soup.find_all('p',class_='topic-info')
    for each in targets:
        try:
            messages.append(each.a.text.split('\n')[1].strip() + each.a.text.split('\n')[2].strip())
        except:
            continue

    result = []
    length = len(title)
    for i in range(length):
        result.append(title[i] + messages[i] + '\n')
    return result

    #找出一共多少页
def find_depth(res):
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    depth = soup.find('li', class_='disable').previous_sibling.previous_sibling.text

    return int(depth)

def main():
    res = "https://xz.aliyun.com/"
    res = open_url(res)
    depth = find_depth(res)

    result = []
    for i in range(depth):
        url = res + '/?page=' + str(2 * i)
        res = open_url(url)
        result.extend(find_title(res))

        with open("先知.txt",'w',encoding='utf-8') as file:
            for each in result:
                file.write(each)
if __name__ == "__main__":
    main()
最佳答案
2020-8-5 14:15:47
Thewhitecrow 发表于 2020-8-4 18:21
报错AttributeError: 'NoneType' object has no attribute 'previous_sibling',我感觉是一共多少页那里有 ...
  1. import requests
  2. import bs4
  3. import re

  4. def open_url(url):

  5.     headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

  6.     res = requests.get(url, headers=headers)
  7.     return res

  8. def find_title(res):
  9.     soup = bs4.BeautifulSoup(res.text,'html.parser')

  10.     #文章标题
  11.     title = []
  12.     targets = soup.find_all('p',class_='topic-summary')
  13.     for each in targets:
  14.         title.append(each.a.text.strip('\n').strip(' '))

  15.     #资料(作者,类型,时间)
  16.     messages = []
  17.     targets = soup.find_all('p',class_='topic-info')
  18.     for each in targets:
  19.             messages.append([each.a.text ,re.search(r"(\d{4}-\d{1,2}-\d{1,2})",each.text).group()])
  20.     result = []
  21.     length = len(title)
  22.     for i in range(length):

  23.         result.append([title[i],messages[i]])
  24.     return result

  25.     #找出一共多少页
  26. def find_depth(res):
  27.     soup = bs4.BeautifulSoup(res.text, 'html.parser')
  28.     depth = soup.select('#Wrapper > div > div.span10 > div > div > div.pagination.clearfix > ul > li:nth-child(2) > a')
  29.     depth = re.search('\d{3}',str(depth))
  30.     return int(depth.group())

  31. def main():
  32.     res = "https://xz.aliyun.com/"
  33.     res1 = open_url(res)
  34.     depth = find_depth(res1)

  35.     result = []
  36.     for i in range(1,depth):
  37.         url = res + '/?page=' + str(2 * i)
  38.         print('正在爬取第',i,'页')
  39.         res2 = open_url(url)
  40.         
  41.         result.extend(find_title(res2))

  42.         with open("先知.txt",'w',encoding='utf-8') as file:
  43.             for each in result:
  44.                 file.write(str(each))
  45.                 file.write('\n')
  46.                 file.write('=============================================')
  47.                 file.write('\n')
  48. if __name__ == "__main__":
  49.     main()
复制代码

代码已改好
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-8-5 15:01:56 | 显示全部楼层
Thewhitecrow 发表于 2020-8-5 14:53
老哥为啥我去复制代码,发现爬虫结果没爬干净,是从7.23开始爬,之前的没有爬到

  1. import requests
  2. import bs4
  3. import re

  4. def open_url(url):

  5.     headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

  6.     res = requests.get(url, headers=headers)
  7.     return res

  8. def find_title(res):
  9.     soup = bs4.BeautifulSoup(res.text,'html.parser')

  10.     #文章标题
  11.     title = []
  12.     targets = soup.find_all('p',class_='topic-summary')
  13.     for each in targets:
  14.         title.append(each.a.text.strip('\n').strip(' '))

  15.     #资料(作者,类型,时间)
  16.     messages = []
  17.     targets = soup.find_all('p',class_='topic-info')
  18.     for each in targets:
  19.             messages.append([each.a.text ,re.search(r"(\d{4}-\d{1,2}-\d{1,2})",each.text).group()])
  20.     result = []
  21.     length = len(title)
  22.     for i in range(length):

  23.         result.append([title[i],messages[i]])
  24.     return result

  25.     #找出一共多少页
  26. def find_depth(res):
  27.     soup = bs4.BeautifulSoup(res.text, 'html.parser')
  28.     depth = soup.select('#Wrapper > div > div.span10 > div > div > div.pagination.clearfix > ul > li:nth-child(2) > a')
  29.     depth = re.search('\d{3}',str(depth))
  30.     return int(depth.group())

  31. def main():
  32.     res = "https://xz.aliyun.com/"
  33.     res1 = open_url(res)
  34.     result = []
  35.     result.extend(find_title(res1))
  36.     depth = find_depth(res1)


  37.     for i in range(1,depth):
  38.         url = res + '/?page=' + str(2 * i)
  39.         print('正在爬取第',i,'页')
  40.         res2 = open_url(url)
  41.         
  42.         result.extend(find_title(res2))

  43.         with open("先知.txt",'w',encoding='utf-8') as file:
  44.             for each in result:
  45.                 file.write(str(each))
  46.                 file.write('\n')
  47.                 file.write('=============================================')
  48.                 file.write('\n')
  49. if __name__ == "__main__":
  50.       main()
复制代码

ok之前没把第一页加进去
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2020-8-4 18:21:19 | 显示全部楼层
报错AttributeError: 'NoneType' object has no attribute 'previous_sibling',我感觉是一共多少页那里有点问题,希望前辈们指点下
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-5 10:41:40 | 显示全部楼层
本帖最后由 suchocolate 于 2020-8-5 10:44 编辑

从网页html看,class为disable的li没有前兄弟节点,所以报错说没有。

Annotation 2020-08-05 100836.png

bs不熟,用xpath写了一个简单的:

  1. import requests
  2. from lxml import etree
  3. import re


  4. def main():
  5.     url = 'https://xz.aliyun.com/'
  6.     headers = {'user-agent': 'firefox'}
  7.     r = requests.get(url, headers=headers)
  8.     html = etree.HTML(r.text)
  9.     trs = html.xpath('//tr')
  10.     for item in trs:
  11.         title = item.xpath('normalize-space(./td/p[@class="topic-summary"]/a[@class="topic-title"]/text())')
  12.         info = item.xpath('./td/p[@class="topic-info"]//text()')
  13.         print('标题:', title)
  14.         print('作者:', info[1])
  15.         print('类型:', info[3])
  16.         print('发布时间:', re.findall('\d{4}(?:-\d{2}){2}', info[4])[0])
  17.         print('='*50)

  18. if __name__ == '__main__':
  19.         main()
复制代码
Annotation 2020-08-05 104358.png


小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-5 13:57:34 | 显示全部楼层
suchocolate 发表于 2020-8-5 10:41
从网页html看,class为disable的li没有前兄弟节点,所以报错说没有。

你这个pycharm有点亮眼啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-5 14:15:47 | 显示全部楼层    本楼为最佳答案   
Thewhitecrow 发表于 2020-8-4 18:21
报错AttributeError: 'NoneType' object has no attribute 'previous_sibling',我感觉是一共多少页那里有 ...
  1. import requests
  2. import bs4
  3. import re

  4. def open_url(url):

  5.     headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

  6.     res = requests.get(url, headers=headers)
  7.     return res

  8. def find_title(res):
  9.     soup = bs4.BeautifulSoup(res.text,'html.parser')

  10.     #文章标题
  11.     title = []
  12.     targets = soup.find_all('p',class_='topic-summary')
  13.     for each in targets:
  14.         title.append(each.a.text.strip('\n').strip(' '))

  15.     #资料(作者,类型,时间)
  16.     messages = []
  17.     targets = soup.find_all('p',class_='topic-info')
  18.     for each in targets:
  19.             messages.append([each.a.text ,re.search(r"(\d{4}-\d{1,2}-\d{1,2})",each.text).group()])
  20.     result = []
  21.     length = len(title)
  22.     for i in range(length):

  23.         result.append([title[i],messages[i]])
  24.     return result

  25.     #找出一共多少页
  26. def find_depth(res):
  27.     soup = bs4.BeautifulSoup(res.text, 'html.parser')
  28.     depth = soup.select('#Wrapper > div > div.span10 > div > div > div.pagination.clearfix > ul > li:nth-child(2) > a')
  29.     depth = re.search('\d{3}',str(depth))
  30.     return int(depth.group())

  31. def main():
  32.     res = "https://xz.aliyun.com/"
  33.     res1 = open_url(res)
  34.     depth = find_depth(res1)

  35.     result = []
  36.     for i in range(1,depth):
  37.         url = res + '/?page=' + str(2 * i)
  38.         print('正在爬取第',i,'页')
  39.         res2 = open_url(url)
  40.         
  41.         result.extend(find_title(res2))

  42.         with open("先知.txt",'w',encoding='utf-8') as file:
  43.             for each in result:
  44.                 file.write(str(each))
  45.                 file.write('\n')
  46.                 file.write('=============================================')
  47.                 file.write('\n')
  48. if __name__ == "__main__":
  49.     main()
复制代码

代码已改好
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2020-8-5 14:42:36 | 显示全部楼层
suchocolate 发表于 2020-8-5 10:41
从网页html看,class为disable的li没有前兄弟节点,所以报错说没有。

老哥我刚才发现你的的class原因,也改了。还是有点问题,debug的时候在有多少页这个地方,语法有问题
  1. import requests
  2. import bs4
  3. import re

  4. def open_url(url):

  5.     headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

  6.     res = requests.get(url, headers=headers)
  7.     return res

  8. def find_title(res):
  9.     soup = bs4.BeautifulSoup(res.text,'html.parser')

  10.     #文章标题
  11.     title = []
  12.     targets = soup.find_all('p',class_='topic-summary')
  13.     for each in targets:
  14.         title.append(each.a.text)

  15.     #资料(作者,类型,时间)
  16.     messages = []
  17.     targets = soup.find_all('p',class_='topic-info')
  18.     for each in targets:
  19.         try:
  20.             messages.append(each.p.text.split('\n')[1].strip() + each.p.text.split('\n')[2].strip())
  21.         except:
  22.             continue

  23.     result = []
  24.     length = len(title)
  25.     for i in range(length):
  26.         result.append(title[i] + messages[i] + '\n')
  27.     return result

  28.     #找出一共多少页
  29. def find_depth(res):
  30.     soup = bs4.BeautifulSoup(res.text, 'html.parser')
  31.     depth = soup.find('li', class_='disabled').previous_sibling.previous_sibling.text

  32.     return int(depth)

  33. def main():
  34.     host = "https://xz.aliyun.com/"
  35.     res = open_url(host)
  36.     depth = find_depth(res)

  37.     result = []
  38.     for i in range(depth):
  39.         url = host + '/?page=' + str(2 + i)
  40.         res = open_url(url)
  41.         result.extend(find_title(res))

  42.         with open("先知.txt",'w',encoding='utf-8') as file:
  43.             for each in result:
  44.                 file.write(each)

  45. if __name__ == "__main__":
  46.     main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-5 14:44:11 | 显示全部楼层

老哥你这真的强,我好像明白了,谢谢老哥
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-5 14:44:44 | 显示全部楼层
suchocolate 发表于 2020-8-5 10:41
从网页html看,class为disable的li没有前兄弟节点,所以报错说没有。

老哥你这我去学习下,非常感谢哥哥
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-5 14:53:13 | 显示全部楼层

老哥为啥我去复制代码,发现爬虫结果没爬干净,是从7.23开始爬,之前的没有爬到
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-5 14:58:51 | 显示全部楼层
Thewhitecrow 发表于 2020-8-5 14:53
老哥为啥我去复制代码,发现爬虫结果没爬干净,是从7.23开始爬,之前的没有爬到

稍等,我改一下代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-5 15:05:30 | 显示全部楼层
1q23w31 发表于 2020-8-5 15:01
ok之前没把第一页加进去

老哥感谢,够自己去反思学习了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-24 20:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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