鱼C论坛

 找回密码
 立即注册
查看: 654|回复: 1

python爬取评论时出错

[复制链接]
发表于 2018-8-27 17:20:35 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 chunguang 于 2018-8-27 17:41 编辑

python爬取评论,但只能爬取每一页的第一条评论,求大神
  1. import requests
  2. import re
  3. import csv
  4. from bs4 import BeautifulSoup
  5. from requests.exceptions import  RequestException
  6. from urllib.parse import  urlencode
  7. from multiprocessing import Pool

  8. def get_comments(url):
  9.     try:
  10.         headers = {
  11.             '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'
  12.         }
  13.         response=requests.get(url,headers=headers)
  14.         response.encoding = 'gbk'
  15.         if response.status_code==200:
  16.             return response.text
  17.         print('请求评论错误')
  18.         return None
  19.     except RequestException:
  20.         return None


  21. def parse_comments(html):
  22.     soup = BeautifulSoup(html, 'lxml')
  23.     items=soup.find_all('body')
  24.     for item in items:
  25.         name = item.select('.username ')[1].text
  26.         rank = item.select('#commentnormalinfo a')[0].text
  27.         comments = item.select('.commenttext')[0].text
  28.         province = item.select('.commentinfo span')[3].text
  29.         price = item.select('.price_num')[0].text
  30.         data={
  31.             'name':name,
  32.             'rank':rank,
  33.             'comments': comments,
  34.             'province': province,
  35.             'price': price
  36.         }
  37.         yield data

  38. def main():
  39.     url = 'http://www.yanyue.cn/product/comments/148?paramsend=postget&productid=148&paramsend=postget&page_offset=1'
  40.     html=get_comments(url)
  41.     for item in parse_comments(html):
  42.         print(item)

  43. if __name__=='__main__':
  44.     main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-8-28 09:02:28 | 显示全部楼层
兄弟,你的解析库使用的有问题,你识别的是所有的body,一个网页中只有一个body,所以你的items 中只有一个元素,当然就只把每一页的第一条评论搞出来了,建议你要是按照标签找的话,先找这个:<ul class="mt10"> 然后再找li的标签。good luck
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-7-1 09:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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